Android Spinner: Get the selected item change event

前端 未结 16 2239
挽巷
挽巷 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:53

    https://stackoverflow.com/q/1714426/811625

    You can avoid the OnItemSelectedListener() being called with a simple check: Store the current selection index in an integer variable and check within the onItemSelected(..) before doing anything.

    E.g:

    Spinner spnLocale;
    
    spnLocale = (Spinner)findViewById(R.id.spnLocale);
    
    int iCurrentSelection = spnLocale.getSelectedItemPosition();
    
    spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 
        if (iCurrentSelection != i){
                // Your code here
        }
        iCurrentSelection = i;
        } 
    
        public void onNothingSelected(AdapterView adapterView) {
            return;
        } 
    }); 
    

    Of cause the iCurrentSelection should be in object scope for this to work!

提交回复
热议问题