如何按值而不是按位置设置 Spinner 的选定项目? [英] How to set selected item of Spinner by value, not by position?
本文介绍了如何按值而不是按位置设置 Spinner 的选定项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个更新视图,我需要在其中为微调器预先选择存储在数据库中的值.
I have a update view, where I need to preselect the value stored in database for a Spinner.
我想到了这样的事情,但是 Adapter
没有 indexOf
方法,所以我被卡住了.
I was having in mind something like this, but the Adapter
has no indexOf
method, so I am stuck.
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
推荐答案
假设你的 Spinner
被命名为 mSpinner
,并且它包含作为它的选择之一:some value".
Suppose your Spinner
is named mSpinner
, and it contains as one of its choices: "some value".
要查找和比较 Spinner 中某个值"的位置,请使用以下命令:
To find and compare the position of "some value" in the Spinner use this:
String compareValue = "some value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (compareValue != null) {
int spinnerPosition = adapter.getPosition(compareValue);
mSpinner.setSelection(spinnerPosition);
}
这篇关于如何按值而不是按位置设置 Spinner 的选定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文