Search code examples
androidspinner

Android: setSelection having no effect on Spinner


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!


Solution

  • Try moving the call to setSelection() after the call to setAdapter().