我有一个更新视图,在那里我需要预先选择存储在数据库中的值为一个微调器。
我有这样的想法,但适配器没有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);
}
当前回答
使用下面的行来选择使用值:
mSpinner.setSelection(yourList.indexOf("value"));
其他回答
使用下面的行来选择使用值:
mSpinner.setSelection(yourList.indexOf("value"));
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
}
这是我的解决方案
List<Country> list = CountryBO.GetCountries(0);
CountriesAdapter dataAdapter = new CountriesAdapter(this,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountries.setAdapter(dataAdapter);
spnCountries.setSelection(dataAdapter.getItemIndexById(userProfile.GetCountryId()));
和下面的getItemIndexById
public int getItemIndexById(String id) {
for (Country item : this.items) {
if(item.GetId().toString().equals(id.toString())){
return this.items.indexOf(item);
}
}
return 0;
}
希望这对你有所帮助!
我正在使用一个自定义适配器,这段代码就足够了:
yourSpinner.setSelection(arrayAdapter.getPosition("Your Desired Text"));
所以,你的代码片段将是这样的:
void setSpinner(String value)
{
yourSpinner.setSelection(arrayAdapter.getPosition(value));
}
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);
}
}