Android: setSelection having no effect on Spinner

Viewed 66145

I'm having some problems with setSelection on a Spinner. I set the value to be pre-selected when the spinner is shown in code, but it has no effect and the first alternative in the list is always selected. The code looks like this:

LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = li.inflate(R.layout.edit_event, null);
...
ArrayList<String> routes = new ArrayList<String>();
// routes filled with values at runtime
...
ArrayAdapter<String> aa = new ArrayAdapter<String>(GOFdroid.this, android.R.layout.simple_spinner_item, routes);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  
Spinner destSpinner = (Spinner) dialogView.findViewById(R.id.edit_event_destination);
  
String dest = events.get(pos).getDestination();
int routesPos = routes.indexOf(dest);
Log.d(TAG, "Dest: " + dest + ", pos: " + routesPos);
destSpinner.setSelection(routesPos);
   
destSpinner.setAdapter(aa);

The code works as intended except for the setSelection-part, and I just can't figure out why.

The XML layout of the spinner looks like this (not the entire layout, only the spinner part):

// DESTINATION
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Destination:" />
<Spinner
   android:id="@+id/edit_event_destination"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:prompt="@string/choose_dest"
   android:layout_marginBottom="10dip"
   android:text="" />

Help is very much appreciated!

11 Answers

Sometimes, we may not set listeners because the spinner may be set to a certain value, and disabled as per requirement.

This can lead to setSelection() not selecting a value, since it needs a listener.

Make sure that the Spinner's setOnItemSelectedListener() is set to a custom listener like below.

Even if the spinner is disabled, we must set a listener like below, so that the setSelection() method works.

spinnerListener.setOnItemSelectedListener(spinnerListener);
AdapterView.OnItemSelectedListener spinnerListener = new 
AdapterView.OnItemSelectedListener() 
{
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
      //Your code
    }
}
spinnerListener.setSelection(0);
Related