我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
当前回答
这是我正在使用的Kotlin扩展:
fun Spinner.setItem(list: Array<CharSequence>, value: String) {
val index = list.indexOf(value)
this.post { this.setSelection(index) }
}
用法:
spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)
其他回答
这招对我很管用:
@Override
protected void onStart() {
super.onStart();
mySpinner.setSelection(position);
}
它类似于@sberezin的解决方案,但在onStart()中调用setSelection()。
Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better. Most popular answer by Arun George is correct but don't work in some cases. The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load. The answer is - you should simply choose correct place to call to setSelection(), for example it works for me: @Override public void onResume() { super.onResume(); yourSpinner.setSelection(pos); } But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic. The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)
是的,您可以通过在spinner的setSelection函数中传递所需spinner项的索引来实现这一点。例如:
spinnerObject.setSelection (INDEX_OF_CATEGORY)。
这是我正在使用的Kotlin扩展:
fun Spinner.setItem(list: Array<CharSequence>, value: String) {
val index = list.indexOf(value)
this.post { this.setSelection(index) }
}
用法:
spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)
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;
}
}
}
你可以使用上面的方法:
selectSpinnerItemByValue(spinnerObject, desiredValue);
&当然你也可以直接按索引选择
spinnerObject.setSelection(index);