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
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.
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.
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);
}
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
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
Try moving the call to setSelection()
after the call to setAdapter()
.