0

I created a spinner with 5 items and I also created 5 buttons. What I want to do is to associate a button to an item in the spinner. So when I click a button, a corresponding item will be selected. For example:

I have 5 items in my spinner:

hey, hi, ho, hello, sup

I have 5 buttons:

btn1, btn2, btn3, btn4, btn5

btn5 is associated to sup. So when I click btn5, sup should be selected in the spinner. How would I do this?

Bram
  • 2,515
  • 6
  • 36
  • 58
yologaming
  • 117
  • 2
  • 10

3 Answers3

0

You have to use

spinner.setSelection(position);
Paritosh
  • 2,097
  • 3
  • 30
  • 42
0

Set an onClickListener on each button calling the following function with the button id as parameter:

function switchSpinner(int id){
    Spinner spinner=(Spinner) findViewById(R.id.spinner);
    int pos=-1;
    switch(id){
        R.id.btn1:
            pos=0;
            break;
        R.id.btn2:
            pos=1;
            break;
        R.id.btn3:
            pos=2;
            break;
        R.id.btn4:
            pos=3;
            break;
        R.id.btn5:
            pos=4;
            break;  
    }
    spinner.setSelection(pos);
    spinner.requestLayout() //add this only if the spinner does not change    
}
Paritosh
  • 2,097
  • 3
  • 30
  • 42
Droidekas
  • 3,464
  • 2
  • 26
  • 40
0

If you need to enter hard code values for spinner then you need to do this

  Button0.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          // Here you need specify which item of spinner you need to select.
         spinner.setSelection(0);
       }
    });

Like this if you have 5 buttons you need to create 5 click event with setSelect(position) event.

You can do this by different ways as you prefer. I think using this you will have more control.

For dynamic spinner you need different logic where you need to create button dynamically and add click event them dynamically with index of your custom or base adapter.

Codelord
  • 1,120
  • 2
  • 10
  • 21