OnItemSelectedListener called on screen rotation

2019-08-03 07:54发布

问题:

When I change the orientation of my screen in Android, an OnItemSelectedListener from a Spinner is called.

It's not just the emulator, it also happens on a physical phone.

How can I stop this from occurring?

Cheers.

回答1:

Spinners are always selected. Your OnItemSelectedListener will be called when there is any change in the state of the Spinner, including when the Spinner is first set up. A normal orientation change will result in your activity being destroyed and recreated. So, if your OnItemSelectedListener is being called when your activity is first appearing on the screen, it will be called again when the orientation is changed.

How can I stop this from occurring?

You might be able to play around with the timing of when you call setOnItemSelectedListener() compared to setAdapter(), to see if it helps.



回答2:

You will also get a second call if the spinner's selectedItemPosition is not zero when the screen is rotated, as Android sets the position to what it was before rotation. Use onSaveInstanceState to count the number of spinners in a none zero position and use this count so that the OnItemSelected code just returns until the count has been decremented to zero.

You also need to be extremely careful with spinners that can have a visibility of View.GONE. I'll add some more text here when I can find the time to describe exactly how to handle these.



回答3:

The OnItemSelectedListener is called before the spinner contains its adapter so you need validate that the view is not null inside OnItemSelected method, like that:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
  @Override public void onItemSelected (AdapterView<?> parent, View view, int position, long id){
    if(view != null) { // <- here is the validation
      // Your code to do something with the selected item
    }
  }
  @Override public void onNothingSelected(AdapterView<?> parent) { }
});