Android: setSelection having no effect on Spinner

AndroidSpinner

Android Problem Overview


I'm having some problem 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!

Linus

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

I had similar problem. In my case setAdaper and setSelection were in correct order! Executed form onCreate worked, but when executed from onResume had no effect.

The solution is to call setSelection(my_pos, true). Notice the second parameter.

Solution 3 - Android

You might try

mSpinner.post(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  });

this will post the runnable action to run as soon as the view is created

Solution 4 - Android

In my case none of the answers worked, so I queued the setSelection through a Handler

new Handler().postDelayed(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  }, 100);

Doing this could cause problems when running on slow devices, but I'm working for a specific device so it's ok to use this hack

Solution 5 - Android

None of the previous answers worked for me. What did work, though, was creating the instance variable mSpinner in the onCreateView() method of my fragment (or in the onCreate() method of your activity), then doing this in my onLoadFinished() method...

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
	adapter.swapCursor(cursor);
    //mSpinner.setAdapter(adapter);
	mSpinner.setSelection(mSelectedIndex);
}

Solution 6 - Android

Spinner.setSelection() do not work if you call it before Spinner.setAdapter()

Try calling setSelection() after the call to setAdapter().

Reason Behind this : when you call Spinner.Selection() before setting an adapter to it simply means that you are trying to set spinner to custom index by setSelection() when it doesn't contain any data or we can say thats spinner has max item =0.

so setSelection(1) means setting index to 1 for spinner which has max item =0; Although spinner itself handles this outofBoundIndex so your app does not crashes.

call to SetSelection() should be after setAdapter() only

Also if you have a Spinner.SetOnItemSelectedListener() and you have problem that onItemSelected(AdapterView<?> parent, View view, int position, long id) is tiggered with position value=0 when activity load and then you should use this pattern.

Spinner.SetAdapter()
Spinner.setSelection();
Spinner.setOnItemSelectedListener();

Solution 7 - Android

>> The solution is to call setSelection(my_pos, true). Notice the second parameter.

Don`t forget, if you call animate, setup layout params then :) Example:

LinearLayout.LayoutParams spinnerLp = (LinearLayout.LayoutParams) spinner.getLayoutParams();
spinner.setSelection(selectedPositionAge, true);
spinnerLp.gravity = Gravity.CENTER;
spinner.setLayoutParams(spinnerLp);

manually setted paddings to spinner needs to be reseted manually

Solution 8 - Android

I had the same problem with a spinner inside a fragment : setSelection works correctly during the onCreate at first start of the activity, but not when I rotate the screen. I solved it by calling setSelection within the onViewStateRestored method of the fragment instead of calling it inside the onCreate method. I'm not sure but I think that you can't use setSelection until the view is fully loaded, even if you can findViewById it.

Solution 9 - Android

use this

    sp2.setAdapter(sp2.getAdapter());
	sp2.getAdapter().notifyDataSetChanged();
	sp2.setSelection(0, false);

Solution 10 - Android

try this, it worked for me:

Spinner destSpinner = (Spinner)dialogView.findViewById(R.id.edit_event_destination);
destSpinner.setSelection(0);
String dest = events.get(pos).getDestination();
int routesPos = routes.indexOf(dest);
destSpinner.setAdapter(aa);
Log.d(TAG, "Dest: " + dest + ", pos: " + routesPos);
destSpinner.setSelection(routesPos);

Solution 11 - Android

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 spinner is disabled, we must set a listener like below, so that 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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaspartameView Question on Stackoverflow
Solution 1 - AndroidCommonsWareView Answer on Stackoverflow
Solution 2 - AndroidGreg DanView Answer on Stackoverflow
Solution 3 - Androiduser2532906View Answer on Stackoverflow
Solution 4 - AndroidMaraguesView Answer on Stackoverflow
Solution 5 - Androidban-geoengineeringView Answer on Stackoverflow
Solution 6 - AndroidsakshamView Answer on Stackoverflow
Solution 7 - AndroidSergey PlahotnickView Answer on Stackoverflow
Solution 8 - AndroidpiiiiippppView Answer on Stackoverflow
Solution 9 - AndroidAli BagheriView Answer on Stackoverflow
Solution 10 - Androidskandhan View Answer on Stackoverflow
Solution 11 - AndroidkoushickView Answer on Stackoverflow