Android Spinner: Get the selected item change event

前端 未结 16 2420
挽巷
挽巷 2020-11-22 16:47

How can you set the event listener for a Spinner when the selected item changes?

Basically what I am trying to do is something similar to this:

spinn         


        
16条回答
  •  面向向阳花
    2020-11-22 17:50

    If you want a true onChangedListener(). Store the initial value in the handler and check to see if it has changed. It is simple and does not require a global variable. Works if you have more than one spinner on the page.

    String initialValue = // get from Database or your object
    mySpinner.setOnItemSelectedListener(new SpinnerSelectedListener(initialValue));
    

    ...

    protected class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {
    
            private SpinnerSelectedListener() {
                super();
            }
    
            public SpinnerSelectedListener(String initialValue) {
                this();
                this.initialValue = initialValue;
            }
    
            private String initialValue;
    
            // getter and setter removed.  
    
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                final String newValue = (String) spinHeight.getItemAtPosition(position);
                if (newValue.equals(initialValue) == false) {
                   // Add your code here.  The spinner has changed value. 
    
                   // Maybe useful.   
                   // initialValue = newValue;
                }
    
            }
    
            @Override
            public void onNothingSelected(AdapterView parent) {
                   // Maybe useful.   
                   // initialValue = null; 
            }
        }
    

    Objects are your friend, use them.

提交回复
热议问题