Reputation: 71
I'm making an App for android. I have 2 spinner
s, and when I select one item in my 1st spinner(simpleSpinner
) it ofc needs to show it(I have done that) but when I select one from my 2nd spinner(multiSpinner
) I want my simpleSpinner
to go back to the first item in the spinner. And the other way around, when I select one in my simpleSpinner
I want my multiSpinner
to show the first item in my simpleSpinner
. How do I do that?
final ArrayAdapter<String> ar1 = new ArrayAdapter<String>(this,
R.layout.my_spinner, arrSimple);
final ArrayAdapter<String> ar2 = new ArrayAdapter<String>(this,
R.layout.my_spinner, arrMulti);
spSimple.setAdapter(ar1);
spMulti.setAdapter(ar2);
AdapterView.OnItemSelectedListener simpleListen = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String simpleText = spSimple.getSelectedItem().toString();
if("Rouge".equals(simpleText)){
spMulti.setSelection(0);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
AdapterView.OnItemSelectedListener multiListen = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String multiText = spMulti.getSelectedItem().toString();
if("Plein".equals(multiText)){
spSimple.setSelection(0);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spSimple.setOnItemSelectedListener(simpleListen);
spMulti.setOnItemSelectedListener(multiListen);
The code works now! Thanks to @BlackPanther
Upvotes: 0
Views: 75
Reputation: 4671
You should use separate listeners for you Spinners
. Since you are using the same listener for both the Spinners
this piece of code
if("Rouge".equals(simpleText)){
spMulti.setSelection(0);
}
causes your problem.
When you have first selected "Rouge" in your first Spinner
the second spinner is set to "Wahie", now when you try to change the item in your second Spinner
, the same method is invoked and since the first Spinner
's selection is in "Rouge" the second Spinner
is set to "Wahie" again..
In your onCreate
method do something like this
@Override
public void onCreate(Bundle savedInstanceState) {
//your code
addListenerOnSpinnerItemSelection();
//more of your code
}
public void addListenerOnSpinnerItemSelection() {
spMulti = (Spinner) findViewById(R.id.spMulti);
spMulti.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
you can create a custom listener class that implements OnItemSelectedListener
see this article. You can adapt from it and tailor it according to your need.
You can use the same listener for both the spinners by the following code
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spSimple)
{
//do this
}
else if(spinner.getId() == R.id.spMulti)
{
//do this
}
Upvotes: 1