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

后端 未结 12 1169
慢半拍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条回答
  •  -上瘾入骨i
    2021-02-02 08:23

    When Spinner.setSelection(position) is used, it always activates setOnItemSelectedListener()

    To avoid firing the code twice I use this solution:

    private mIsSpinnerFirstCall=true;
    
    ...
    Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView parent, View view, int position, long id) {
            //If a new value is selected (avoid activating on setSelection())
            if(!mIsSpinnerFirstCall) {
                // Your code goes gere
            }
            mIsSpinnerFirstCall = false;
        }
    
        public void onNothingSelected(AdapterView arg0) {
        }
    });
    

    This solution is valid when you are sure that Spinner.setSelection(position) us used. Also, it is important to set mIsSpinnerFirstCall=true each time before using Spinner.setSelection(position)

提交回复
热议问题