Android:setSelection对Spinner没有影响

asp*_*ame 47 android spinner

我在Spinner上遇到setSelection问题.我在代码中显示微调器时将值设置为预选,但它没有任何效果,并且始终选择列表中的第一个选项.代码如下所示:

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View dialogView = li.inflate(R.layout.edit_event, null);
    ...
    ArrayList<String> routes = new ArrayList<String>();
    // routes filled with values at runtime
    ...
    ArrayAdapter<String> aa = new ArrayAdapter<String>(GOFdroid.this, android.R.layout.simple_spinner_item, routes);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    Spinner destSpinner = (Spinner) dialogView.findViewById(R.id.edit_event_destination);

    String dest = events.get(pos).getDestination();
    int routesPos = routes.indexOf(dest);
    Log.d(TAG, "Dest: " + dest + ", pos: " + routesPos);
    destSpinner.setSelection(routesPos);

    destSpinner.setAdapter(aa);
Run Code Online (Sandbox Code Playgroud)

除了setSelection-part之外,代码按预期工作,我无法弄清楚原因.

微调器的XML布局看起来像这样(不是整个布局,只有微调器部分):

// DESTINATION
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Destination:" />
<Spinner
   android:id="@+id/edit_event_destination"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:prompt="@string/choose_dest"
   android:layout_marginBottom="10dip"
   android:text="" />
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助!

莱纳斯

Com*_*are 114

尝试在通话setSelection()结束后将通话移至setAdapter().

  • 嘿.已经在setAdapter之后放了setSelection,它仍然无法正常工作.它显示的是位于列表顶部的那个而不是我想要显示的那个. (11认同)
  • 太容易了!;)谢谢commonsware,再次为我节省了一些时间! (3认同)

Gre*_*Dan 67

我有类似的问题.在我的情况下setAdaper,setSelection并在正确的顺序!执行的表单onCreate有效,但执行onResume时没有效果.

解决方案是调用setSelection(my_pos, true).注意第二个参数.

  • 谢谢 !我永远不会想象一个名为'animate'的参数会产生这种效果...... (6认同)
  • 非常感谢。我开始认为我是问题所在。 (2认同)

小智 34

你可以试试

mSpinner.post(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  });
Run Code Online (Sandbox Code Playgroud)

这将在创建视图后立即发布runnable操作

  • 没有延迟甚至更好,它似乎也有效. (2认同)

Mar*_*ues 26

在我的情况下,没有一个答案有效,所以我通过Handler将setSelection排队

new Handler().postDelayed(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  }, 100);
Run Code Online (Sandbox Code Playgroud)

这样做可能会导致在慢速设备上运行时出现问题,但我正在为特定设备工作,因此可以使用此hack

  • 谢谢,因为没有别的办法了...但是它给我一种不好的感觉 (2认同)