aspartame
aspartame

Reputation: 4662

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!

Upvotes: 57

Views: 69541

Answers (11)

Ali Bagheri
Ali Bagheri

Reputation: 3419

use this

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

Upvotes: 1

Sergey Plahotnick
Sergey Plahotnick

Reputation: 11

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 set paddings to spinner need to be reset manually.

Upvotes: 1

koushick
koushick

Reputation: 166

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

Upvotes: 0

Boycott A.I.
Boycott A.I.

Reputation: 18871

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

Upvotes: 4

saksham
saksham

Reputation: 3324

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

Upvotes: 4

skandhan
skandhan

Reputation: 41

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

Upvotes: 0

user2532906
user2532906

Reputation: 411

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

Upvotes: 41

piiiiipppp
piiiiipppp

Reputation: 11

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.

Upvotes: 1

Maragues
Maragues

Reputation: 38324

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

Upvotes: 31

Greg Dan
Greg Dan

Reputation: 6298

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.

Upvotes: 75

CommonsWare
CommonsWare

Reputation: 1006614

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

Upvotes: 142

Related Questions