Tuesday, February 21, 2012

Using spinner.setSelection & finding the spinner doesn't show the selected item when closed in android?


Ok, I've just spent a couple of hours trying to figure this out, and now I have, I thought I'd share the incredibly simple solution with you.

The issue: I was needing to set a Spinner's 
selected item via code, but found when calling the Spinner's setSelection method and passing in the position to set it to, something odd would happen, the closed spinner would appear blank, yet, when clicking on it, the item I've asked to be selected would be correctly located at the top of the spinner.

It looks like a Spinner is not told to redraw when using
.setSelection(position), what you have to do is call.setSelection(int position, boolean animate) unless you want your selection to happen silently behind the scenes.

Odd, but easily sorted out.

The incredibly simple solution:

This 
won't show the fact that the Spinner selection has been set:

spnIngredients.setAdapter(ingredientAdapter);
spnIngredients.setSelection(position);

This will:

spnIngredients.setAdapter(ingredientAdapter);
spnIngredients.setSelection(pos, true);

1 comment:

  1. Thank you so much for posting this! I don't think I would ever have figured-out this bug otherwise. :)

    ReplyDelete