简体   繁体   English

Android Spinner.setSelection()不起作用

[英]Android Spinner.setSelection() doesn't work

I'm having a spinner which is populated with a CursorAdapter . 我有一个用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) 现在,当创建该微调器(动态)时,我想将默认选择设置为0(0是CursorAdapter列表中的第一个项)

So I got a setter for that job that is just called after the object has been created. 所以我得到了一个在创建对象后调用的作业的setter。 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 . 但由于某种原因,无论我在该setter中传递什么,0总是传递给Spinner的OnItemSelectedListeneronItemSelected()方法。

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 setter运行,一个数字,让我们说4(微调器包含多于4个选项的方式)被传递给setSelection()方法
  • WAIT A BIT 稍等一会
  • NOW onItemSelected() is run the first time, but the position given to that method is 0! 现在onItemSelected()第一次运行,但给该方法的位置是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! 再次onItemSelected()运行,这个时间,给出的位置是4,因为它应该是!

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. 似乎不可能设置该微调器直到第一个初始选择(始终为0)运行。 So why is it the way it is and what can I do to set the initial selection? 那么为什么它是这样的,我该怎么做才能设置初始选择?

Try Spinner#setSelection (int position, boolean animate) with animate = false. 尝试使用animate = false的Spinner#setSelection (int position, boolean animate) 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. 内部实现似乎与动画部分的差异有所不同。

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. 更改微调器项目选择时,将调用onItemselectedlistener。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM