Home >Java >javaTutorial >How to Programmatically Set the Selected Item in an Android Spinner by Value?
Setting Selected Item of Spinner by Value
When updating a view, you may encounter the need to preselect a value stored in the database for a Spinner. Initially, you might attempt a solution such as:
void setSpinner(String value) { int pos = getSpinnerField().getAdapter().indexOf(value); getSpinnerField().setSelection(pos); }
However, this approach encounters a roadblock as the Adapter interface does not provide an indexOf method.
Solution
To find and compare the position of a specific value within your Spinner, follow these steps:
Create an ArrayAdapter using the required resource:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
Set the ArrayAdapter as the Adapter for your Spinner:
mSpinner.setAdapter(adapter);
Use the getPosition method to determine the position of your comparison value within the ArrayAdapter:
if (compareValue != null) { int spinnerPosition = adapter.getPosition(compareValue); mSpinner.setSelection(spinnerPosition); }
By following these steps, you can effectively preselect a value in a Spinner based on its value rather than its position in the list.
The above is the detailed content of How to Programmatically Set the Selected Item in an Android Spinner by Value?. For more information, please follow other related articles on the PHP Chinese website!