OnItemSelectedListener called on screen rotation

拟墨画扇 提交于 2019-12-11 06:44:23

问题


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) { }
});


来源:https://stackoverflow.com/questions/4234668/onitemselectedlistener-called-on-screen-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!