Android Spinner.setSelection() doesn't work

2019-02-16 12:46发布

I'm having a spinner which is populated with a CursorAdapter. Now when creating that spinner (dynamically) I want to set a default selection different to 0 (0 being the first item in the CursorAdapter list)

So I got a setter for that job that is just called after the object has been created. But for some reason, no matter what I pass in that setter, 0 always is passed to the onItemSelected() method within the Spinner's OnItemSelectedListener.

HOWEVER if I just wait till the first initial selection happened and run my setter again, everything works fine. So, to make it more clear here is what I see in the debugger:

  • object (spinner) is created
  • spinner listener is attached
  • setter is run, a number, lets say 4 (the spinner contains way more than 4 selections) is passed to the setSelection() method
  • WAIT A BIT
  • NOW onItemSelected() is run the first time, but the position given to that method is 0!
  • WAIT A BIT MORE
  • again we run the setter
  • again onItemSelected() is run, THIS TIME, the position given is 4 as it was supposed to be!

Now that's wired. It doesn't seem to be possible to set that spinner till the first initial selection, which is always 0, was run. So why is it the way it is and what can I do to set the initial selection?

2条回答
迷人小祖宗
2楼-- · 2019-02-16 13:17

Try Spinner#setSelection (int position, boolean animate) with animate = false. I remember a while back I had a similar problem and this did the trick. The internal implementation seems to differ apart from the difference coming from the animate part.

查看更多
该账号已被封号
3楼-- · 2019-02-16 13:25

If you know default selected spinner item, it can be written as follows:

Spinner sp = (Spinner) findViewById(R.id.spinner);
sp.setSelection(0);   // sets the first item 

onItemselectedlistener is called when you change the spinner item selection.

查看更多
登录 后发表回答