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 }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With