我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
我在一个android项目上工作,我正在使用一个旋转器,它使用一个从数据库填充的数组适配器。
我不知道如何从列表中以编程方式设置所选项目。例如,如果在旋转器中有以下项目:
类别1 第二类 3级
当创建屏幕时,我如何通过编程使类别2成为所选项目。我在想它可能类似于c#的i.e. Spinner。SelectedText = "Category 2"但似乎没有任何方法类似于Android。
当前回答
是的,您可以通过在spinner的setSelection函数中传递所需spinner项的索引来实现这一点。例如:
spinnerObject.setSelection (INDEX_OF_CATEGORY)。
其他回答
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);
如果你有一个联系人列表,你可以这样做:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
是的,您可以通过在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)
我从昨天开始就有同样的问题。不幸的是,数组列表中的第一项默认显示在spinner小部件中。一种转换方法是在数组列表中找到带有每个元素的前一个选定项,并将其与第一个元素交换位置。这是代码。
OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
Collections.swap(yourArrayList,before_index,0);
}
adapter = new ArrayAdapter<String>(CurrentActivity.this,
android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item; yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
String strName = "";
int swap_index = 0;
for (int i=0;i<societies.size();i++){
strName = yourArrayList.get(i);
if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
swap_index = i;
isFound = true;
}
}
return swap_index;
}