问题
I preparing a form in which i have to use same page for Adding details and Editing details. While adding details all fields will be blank and spinner selection will be set to "no selection". Now i want to set the spinner selection of the item which i am going to pass from the previous activity. How to achieve this ?? As spinner does not have any method something like, setSelection(String string); Or is there any other way, i can achieve this mechanism...
Would anyone please help me...
回答1:
This is what i did and it seems to work fine
Spinner my_spinner=(Spinner)findViewById(R.id.spn_items);
ArrayAdapter<String> array_spinner=(ArrayAdapter<String>)my_spinner.getAdapter();
my_spinner.setSelection(array_spinner.getPosition("list item"));
回答2:
I dont now how frequently this might be used but we can set selection of the spinner by text inside it. Spinner has the method setSelection(int position);.
Now in the parameter we need to pass position of the text, which we can get from the array_list we use to bind to adapter, by getIndexOf(Object object)
and object should be of the type of ArrayList
that is declared For example, if ArrayList
is of type String, the object to be passed to getIndexOf(Object object)
should be of type String.
Finally, you set selection as below:
spinner.setSelection ( spinner_array_list.indexOf(string) );
来源:https://stackoverflow.com/questions/15675153/how-to-set-spinner-selection-by-text-inside-it