Preselecting an Item in Spinner Based on Value
When updating a view, it's often necessary to preselect a value stored in a database for a Spinner control. The default approach using the Adapter's indexOf method is limited.
Instead, you can achieve this preselection by comparing the target value to the Spinner's items using an ArrayAdapter. Here's an example:
<code class="java">public void setSpinner(String value) { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (value != null) { int spinnerPosition = adapter.getPosition(value); getSpinnerField().setSelection(spinnerPosition); } }</code>
In this code:
This approach allows you to preselect an item in a Spinner based on the stored value, not by its position. It's a clean and efficient solution for updating views with specific data.
The above is the detailed content of How to Preselect an Item in a Spinner Based on Value in Android?. For more information, please follow other related articles on the PHP Chinese website!