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

后端 未结 12 1170
慢半拍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:35

    My solution is very easy. First initialize a global boolean variable.

    boolean shouldWork = true;
    

    Then use below code in your onCreate() method.

    Spinner spinner = findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
            if (shouldWork) {
                   // Do your actions here
            }
            else
                shouldWork = true;
        }
        public void onNothingSelected(AdapterView parentView)  {
    
        }
    });
    

    Now you can use the setSelection method in everwhere without invoking the onItemSelected() method by below code.

    shouldWork = false;
    spinner.setSelection(0);
    

提交回复
热议问题