本文翻译自:Set selected item of spinner programmatically
I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database. 我正在研究一个android项目,我正在使用一个使用数组适配器的微调器,该数组适配器是从数据库中填充的。
I can't find out how I can set the selected item programmatically from the list. 我无法找到如何从列表中以编程方式设置所选项目。 For example if, in the spinner I have the following items: 例如,如果在微调器中我有以下项目:
- Category 1 第1类
- Category 2 第2类
- Category 3 第3类
How would I programmatically make Category 2 the selected item when the screen is created. 创建屏幕时,如何以编程方式将类别2设为选定项目。 I was thinking it might be similar to c# IE Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android. 我认为它可能类似于c#IE Spinner.SelectedText =“Category 2”但似乎没有任何类似于Android的方法。
#1楼
参考:https://stackoom.com/question/kSTw/以编程方式设置微调器的选定项
#2楼
使用以下命令: spinnerObject.setSelection(INDEX_OF_CATEGORY2)
。
#3楼
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
You can use the above like: 您可以使用以上内容:
selectSpinnerItemByValue(spinnerObject, desiredValue);
& of course you can also select by index directly like 当然你也可以直接选择索引
spinnerObject.setSelection(index);
#4楼
I have a SimpleCursorAdapter so I have to duplicate the data for use the respose in this post. 我有一个SimpleCursorAdapter所以我必须复制数据以便在这篇文章中使用respose。 So, I recommend you try this way: 所以,我建议你尝试这种方式:
for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
if (spinnerRegion.getItemIdAtPosition(i) == Integer
.valueOf(signal.getInt(signal
.getColumnIndexOrThrow("id_region")))) {
spinnerRegion.setSelection(i);
break;
}
}
I think that is a real way 我认为这是一个真实的方式
#5楼
No one of these answers gave me the solution, only worked with this: 这些答案中没有一个给我解决方案,只有这个:
mySpinner.post(new Runnable() {
@Override
public void run() {
mySpinner.setSelection(position);
}
});
#6楼
如果你有一个联系人列表,你可以这样做:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));