我有一个更新视图,在那里我需要预先选择存储在数据库中的值为一个微调器。
我有这样的想法,但适配器没有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);
}
当前回答
我正在使用一个自定义适配器,这段代码就足够了:
yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));
所以,你的代码片段将是这样的:
void setSpinner(String value)
{
yourSpinner.setSelection(arrayAdapter.getPosition(value));
}
其他回答
基于值设置微调器的一个简单方法是
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
复杂代码的方法已经有了,这只是简单得多。
I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
cursor.moveToFirst();
int row_count = 0;
int spinner_row = 0;
while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the
// ID is found
int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));
if (knownID==cursorItemID){
spinner_row = row_count; //set the spinner row value to the same value as the cursor row
}
cursor.moveToNext();
row_count++;
}
}
spinner.setSelection(spinner_row ); //set the selected item in the spinner
}
你必须传递你的自定义适配器的位置,如REPEAT[position]。它能正常工作。
你可以使用这种方式,只是让你的代码更简单、更清晰。
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCountry.getAdapter();
int position = adapter.getPosition(obj.getCountry());
spinnerCountry.setSelection(position);
希望能有所帮助。
YourAdapter yourAdapter =
new YourAdapter (getActivity(),
R.layout.list_view_item,arrData);
yourAdapter .setDropDownViewResource(R.layout.list_view_item);
mySpinner.setAdapter(yourAdapter );
String strCompare = "Indonesia";
for (int i = 0; i < arrData.length ; i++){
if(arrData[i].getCode().equalsIgnoreCase(strCompare)){
int spinnerPosition = yourAdapter.getPosition(arrData[i]);
mySpinner.setSelection(spinnerPosition);
}
}