Android Spinner: Get the selected item change event

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

    Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:

    A spinner does not support item click events. Calling this method will raise an exception.

    Better use OnItemSelectedListener() instead:

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView parentView, View selectedItemView, int position, long id) {
            // your code here
        }
    
        @Override
        public void onNothingSelected(AdapterView parentView) {
            // your code here
        }
    
    });
    

    This works for me.

    Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.

提交回复
热议问题