Android Spinner set Selected Item by Value

The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));

 private int getIndex(Spinner spinner, String myString){

  int index = 0;

  for (int i=0;i<spinner.getCount();i++){
   if (spinner.getItemAtPosition(i).equals(myString)){
    index = i;
  return index;
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(;
for(i=0; i < adapter.getCount(); i++) {

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.