Android Spinner: Get the selected item change event
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.
Spinner spnLocale = (Spinner)findViewById(R.id.spnLocale);
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
Note: Remember one thing.
Spinner OnItemSelectedListener
event will execute twice:
- Spinner initialization
- User selected manually
Try to differentiate those two by using flag variable.