I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database.
I can't find out how I can set the selected item programmatically from the list. For example if, in the spinner I have the following items:
How would I programmatically make Category 2 the selected item when the screen is created. I was thinking it might be similar to c# I.E Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android.
Yes, you can achieve this by passing the index of the desired spinner item in the setSelection function of spinner. For example: spinnerObject. setSelection(INDEX_OF_CATEGORY).
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.
To get which item was selected, there is a method of the ListView called getItemAtPosition. Add this line to your OnItemClick method: String itemValue = (String) theListView. getItemAtPosition( position );
Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2)
.
No one of these answers gave me the solution, only worked with this:
mySpinner.post(new Runnable() { @Override public void run() { mySpinner.setSelection(position); } });
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