Sunday, August 1, 2010

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



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




Hope that helps someone out there.
.. Happy Spinning.

9 comments:

  1. Hey,

    Thanks for your simple but useful post! Saved me a while, you would have thought that re-drawing would have been the default eh? :)

    Andy

    ReplyDelete
  2. thanks for the post...!! i'm currently working on an android project right now...and your post, do help me!

    ReplyDelete
  3. Thanks this was driving me nuts! It's so odd because the size of the spinner was even growing to fit the new text, but it was just not changing the text itself.

    ReplyDelete
  4. Many thanks, dude, saved my day. [ps omg what is wrong with it, why on earth would it not invalidate when setting selection]

    ReplyDelete
  5. Man, I was tearing my hair out until I found this post. Thanks a lot!

    ReplyDelete
  6. Wow I just spent so long trying to figure this out. THANKS for stopping me from wasting more time. I am about to do a find and replace on all my setSelection() calls.

    ReplyDelete
  7. Another thing I've noticed is that you must call setAdapter before setSelection, or setSelection doesn't work. Obvious in hindsight... now if only I could figure out how to initialize the spinner to be blank and not call "onItemSelected" spuriously.

    ReplyDelete