Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Spinner: Get the selected item change event

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:

spinner1.onSelectionChange = handleSelectionChange;  void handleSelectionChange(Object sender){     //handle event } 
like image 738
Soni Ali Avatar asked Aug 26 '09 20:08

Soni Ali


People also ask

Which function is used to get the selected item from the spinner?

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. The AdapterView. OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods. Spinner spinner = (Spinner) findViewById(R.

How do I get the spinner selected value in Kotlin?

This example demonstrates how to get Spinner value in Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is spinner in Android with example?

Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it.


1 Answers

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.

like image 52
znq Avatar answered Sep 18 '22 16:09

znq