Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected item of spinner programmatically

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:

  • Category 1
  • Category 2
  • Category 3

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.

like image 264
Boardy Avatar asked Jun 17 '12 15:06

Boardy


People also ask

How to set an item in spinner?

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).

What is set spinner show () method?

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.

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

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 );


2 Answers

Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

like image 183
Arun George Avatar answered Sep 18 '22 21:09

Arun George


No one of these answers gave me the solution, only worked with this:

mySpinner.post(new Runnable() {     @Override     public void run() {         mySpinner.setSelection(position);     } }); 
like image 41
Marco Hernaiz Avatar answered Sep 17 '22 21:09

Marco Hernaiz