Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected

后端 未结 8 1039
执念已碎
执念已碎 2021-02-03 20:52

When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during a

相关标签:
8条回答
  • 2021-02-03 21:30

    Just use setSelection(#, false) before setting the listener:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        spinner.setSelection(2, false);
        spinner.setOnItemSelectedListener(this);
    }
    

    The key is the second parameter. It says to not animate the transition, executing the action immediately and preventing onItemSelected from being fired twice, because a call is already made by the system.

    0 讨论(0)
  • 2021-02-03 21:33

    In general, there seem to be many events that trigger the onItemSelected call, and it is difficult to keep track of all of them. This solution allows you to only respond to user-initiated changes using an OnTouchListener.

    Create your listener for the spinner:

    public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
    
        boolean userSelect = false;
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            userSelect = true;
            return false;
        }
    
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (userSelect) { 
                // Your selection handling code here
                userSelect = false;
            }
        }
    
    }
    

    Add the listener to the spinner as both an OnItemSelectedListener and an OnTouchListener:

    SpinnerInteractionListener listener = new SpinnerInteractionListener();
    mSpinnerView.setOnTouchListener(listener);
    mSpinnerView.setOnItemSelectedListener(listener);
    
    0 讨论(0)
提交回复
热议问题