How to disable onItemSelectedListener to be invoked when setting selected item by code

后端 未结 12 1168
慢半拍i
慢半拍i 2021-02-02 08:05

Just wondering how you handle the following problem: a result is calculated depending on two spinners\' selected items. To handle the UI things, i.e. a user picks a new item in

12条回答
  •  被撕碎了的回忆
    2021-02-02 08:24

    A cleaner solution, in my opinion, to differentiate between programmatic and user-initiated changes is the following:

    Create your listener for the spinner as both an OnTouchListener and OnItemSelectedListener

    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 registering for both event types

    SpinnerInteractionListener listener = new SpinnerInteractionListener();
    mSpinnerView.setOnTouchListener(listener);
    mSpinnerView.setOnItemSelectedListener(listener);
    

    This way, any unexpected calls to your handler method due to initialization or re-initialization will be ignored.

提交回复
热议问题