Android:setSelection 对 Spinner 没有影响

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1484528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:07:57  来源:igfitidea点击:

Android: setSelection having no effect on Spinner

androidspinner

提问by aspartame

I'm having some problem with setSelection on a Spinner. I set the value to be pre-selected when the spinner is shown in code, but it has no effect and the first alternative in the list is always selected. The code looks like this:

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

The code works as intended except for the setSelection-part, and I just can't figure out why.

除了 setSelection-part 之外,代码按预期工作,我就是不知道为什么。

The XML-layout of the spinner looks like this (not the entire layout, only the spinner 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="" />

Help is very much appreciated!

非常感谢帮助!

Linus

莱纳斯

回答by CommonsWare

Try moving the call to setSelection()after the call to setAdapter().

尝试在调用setSelection()之后将调用移到setAdapter()

回答by Greg Dan

I had similar problem. In my case setAdaperand setSelectionwere in correct order! Executed form onCreateworked, but when executed from onResumehad no effect.

我有类似的问题。就我而言setAdapersetSelection顺序正确!执行的形式onCreate有效,但执行时onResume无效。

The solutionis to call setSelection(my_pos, true). Notice the second parameter.

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

回答by user2532906

You might try

你可以试试

mSpinner.post(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  });

this will post the runnable action to run as soon as the view is created

这将在创建视图后立即发布可运行的操作

回答by Maragues

In my case none of the answers worked, so I queued the setSelection through a Handler

在我的情况下,没有一个答案起作用,所以我通过一个处理程序将 setSelection 排队

new Handler().postDelayed(new Runnable() {        
    public void run() {
      mSpinner.setSelection(1);
    }
  }, 100);

Doing this could cause problems when running on slow devices, but I'm working for a specific device so it's ok to use this hack

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

回答by saksham

Spinner.setSelection()do not work if you call it before Spinner.setAdapter()

Spinner.setSelection()如果您之前调用它,则不起作用 Spinner.setAdapter()

Try calling setSelection()after the call to setAdapter().

尝试setSelection()在调用 setAdapter() 之后调用。

Reason Behind this: when you call Spinner.Selection()before setting an adapter to it simply means that you are trying to set spinner to custom index by setSelection() when it doesn't contain any data or we can say thats spinner has max item =0.

这背后的原因:当您Spinner.Selection()在为其设置适配器之前调用时,仅意味着您正在尝试通过 setSelection() 将微调器设置为自定义索引,而它不包含任何数据,或者我们可以说微调器具有最大项目 = 0。

so setSelection(1)means setting index to 1 for spinner which has max item =0; Although spinner itself handles this outofBoundIndex so your app does not crashes.

所以setSelection(1)意味着将最大项目=0的微调器的索引设置为1;尽管 Spinner 本身会处理这个 outofBoundIndex ,因此您的应用程序不会崩溃。

call to SetSelection()should be after setAdapter() only

调用SetSelection()应该只在 setAdapter() 之后

Also if you have a Spinner.SetOnItemSelectedListener()and you have problem that onItemSelected(AdapterView<?> parent, View view, int position, long id)is tiggered with position value=0 when activity load and then you should use this pattern.

此外,如果您有一个Spinner.SetOnItemSelectedListener()问题,onItemSelected(AdapterView<?> parent, View view, int position, long id)并且在活动加载时位置值=0,那么您应该使用此模式。

Spinner.SetAdapter()
Spinner.setSelection();
Spinner.setOnItemSelectedListener();

回答by Ali Bagheri

use this

用这个

    sp2.setAdapter(sp2.getAdapter());
    sp2.getAdapter().notifyDataSetChanged();
    sp2.setSelection(0, false);

回答by ban-geoengineering

None of the previous answers worked for me. What did work, though, was creating the instance variable mSpinnerin the onCreateView()method of my fragment (or in the onCreate()method of your activity), then doing this in my onLoadFinished()method...

以前的答案都不适合我。但是,有效的是mSpinneronCreateView()我的片段的onCreate()方法(或您的活动的方法)中创建实例变量,然后在我的onLoadFinished()方法中执行此操作...

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    adapter.swapCursor(cursor);
    //mSpinner.setAdapter(adapter);
    mSpinner.setSelection(mSelectedIndex);
}

回答by Sergey Plahotnick

The solution is to call setSelection(my_pos, true). Notice the second parameter.

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

Don`t forget, if you call animate, setup layout params then :) Example:

不要忘记,如果您调用 animate,则设置布局参数 :) 示例:

LinearLayout.LayoutParams spinnerLp = (LinearLayout.LayoutParams) spinner.getLayoutParams();
spinner.setSelection(selectedPositionAge, true);
spinnerLp.gravity = Gravity.CENTER;
spinner.setLayoutParams(spinnerLp);

manually setted paddings to spinner needs to be reseted manually

手动设置的填充到微调器需要手动重置

回答by piiiiipppp

I had the same problem with a spinner inside a fragment : setSelectionworks correctly during the onCreateat first start of the activity, but not when I rotate the screen. I solved it by calling setSelectionwithin the onViewStateRestoredmethod of the fragment instead of calling it inside the onCreatemethod. I'm not sure but I think that you can't use setSelectionuntil the view is fully loaded, even if you can findViewByIdit.

在活动的第一次开始fragment : setSelection期间,我在 a 内部的微调器工作正常时遇到了同样的问题onCreate,但在我旋转屏幕时却没有。我通过在片段的方法内调用而不是setSelectiononViewStateRestored方法内调用来解决它onCreate。我不确定,但我认为setSelection在视图完全加载之前你不能使用,即使你可以使用findViewById

回答by skandhan

try this, it worked for me:

试试这个,它对我有用:

Spinner destSpinner = (Spinner)dialogView.findViewById(R.id.edit_event_destination);
destSpinner.setSelection(0);
String dest = events.get(pos).getDestination();
int routesPos = routes.indexOf(dest);
destSpinner.setAdapter(aa);
Log.d(TAG, "Dest: " + dest + ", pos: " + routesPos);
destSpinner.setSelection(routesPos);