ignore OnItemSelectedListener firing on create

后端 未结 5 1513
悲&欢浪女
悲&欢浪女 2021-02-19 06:48

I\'m creating a spinner and I\'ve added an OnItemSelectedListener to it. However I\'ve noticed that it fires on create. Now I was wondering if there wa

5条回答
  •  不思量自难忘°
    2021-02-19 07:20

    Here is my solution.

    I need to ignore the first item selection event because there is a dependency between the Route Grade Spinner and the Route Checkbox.

    And all my controls are setup based on a previous visit to the activity.

    // Used to count the number of times the onItemSelected gets fired
    private int mGradeSelectionCount = 0;
    
    private void attachHandlers() {
        OnItemSelectedListener gradeRangeSelectionMadeListener;
        gradeRangeSelectionMadeListener = new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapter, View view, int position, long id) {
                // If the counter is 0 then we can assume that it is android firing the event
                if (mGradeSelectionCount++ < 1) {
                    return;
                }
                if (mCmbGradeFrom.getSelectedItemPosition() == 0) {
                    // Uncheck the Route checkbox
                    mChkTypeRoute.setChecked(false);
                } else {
                    // Check the Route checkbox
                    mChkTypeRoute.setChecked(true);
                }
            }
            @Override
            public void onNothingSelected(AdapterView arg0) {
                // Dont care, keep the same values as before
    
            }
        };
        mCmbGradeFrom.setOnItemSelectedListener(gradeRangeSelectionMadeListener);
        mChkTypeRoute.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    mCmbGradeFrom.setSelection(0);
                    mCmbGradeTo.setSelection(0);
                }
            }
        });
    }
    

提交回复
热议问题