我有一个更新视图,在那里我需要预先选择存储在数据库中的值为一个微调器。
我有这样的想法,但适配器没有indexOf方法,所以我被卡住了。
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
我有一个更新视图,在那里我需要预先选择存储在数据库中的值为一个微调器。
我有这样的想法,但适配器没有indexOf方法,所以我被卡住了。
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
当前回答
下面是如何做到这一点,如果你使用SimpleCursorAdapter(其中columnName是你用来填充你的spinner的db列的名称):
private int getIndex(Spinner spinner, String columnName, String searchString) {
//Log.d(LOG_TAG, "getIndex(" + searchString + ")");
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
int initialCursorPos = cursor.getPosition(); // Remember for later
int index = -1; // Not found
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
index = i; // Found!
break;
}
}
cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.
return index;
}
}
同样(对Akhil的回答进行了细化),如果你从数组中填充你的Spinner,这是相应的方法:
private int getIndex(Spinner spinner, String searchString) {
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
return i; // Found!
}
}
return -1; // Not found
}
};
其他回答
假设你的Spinner名为mSpinner,它包含一个选项:"some value"。
要查找并比较“some value”在Spinner中的位置,请使用以下命令:
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);
}
如果你使用字符串数组,这是最好的方法:
int selectionPosition= adapter.getPosition("YOUR_VALUE");
spinner.setSelection(selectionPosition);
假设您需要从资源的字符串数组填充微调器,并且希望保持从服务器选择的值。 这是在旋转器中从服务器中设置选定值的一种方法。
pincodeSpinner.setSelection(resources.getStringArray(R.array.pincodes).indexOf(javaObject.pincode))
希望能有所帮助! 另外,代码是在Kotlin!
非常简单,只需使用getSelectedItem();
eg :
ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainType.setAdapter(type);
String group=mainType.getSelectedItem().toString();
上述方法返回一个字符串值
在上面的R.array。Admin_type是值中的字符串资源文件
只需在值>>字符串中创建一个.xml文件
我在Spinners中保留了一个单独的数组列表。这样我就可以在数组列表上执行indexOf,然后使用该值在Spinner中设置选择。