问题
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText2"
android:layout_marginTop="22dp"
android:entries="@array/categorylist"
android:prompt="@string/category" />
i have created spinner in the above format!
final Spinner spnr= (Spinner)findViewById(R.id.spinner1);
String category=spnr.getSelectedItem().toString();
pushed the spinner values in db by getting value in above format.
now when values retrieved from db. the spinner should set according to specific value... how can i implement any ideas pls??
回答1:
That can be possible only when you store the array of the items that are set as entries of Spinner. You can set the position of the selected item in spinner. So you have to find out index of the item that you query from the database. Load the StringArray of categorylist and iterate the array and compare each item with the item fetched from the database. Then set the index of the found item as selected item in spinner.
String[] list = getResources().getStringArray(R.array.categorylist);
int index = 0;
for(String item : list) {
if(item.equals("your_item")){
break;
}
index++;
}
spinner.setSelection(index);
回答2:
Well by using setSelection() you can set particular selection for the spinner rather than the first one (by default). Now your question would be how to get position from the value that you have. So here is the code to do that:
String yourString = "some value"; //the value you want the position for
ArrayAdapter yourAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = yourAdap.getPosition(yourString);
//set the default according to value
spnr.setSelection(spinnerPosition);
来源:https://stackoverflow.com/questions/12628348/android-spinner-setting-value-when-re