Home >Java >javaTutorial >How to Set a Spinner\'s Selection by Value, Not Position in Android?
Setting Spinner's Selection by Value, Not Position
When updating a view and the Spinner's selection must match a value stored in the database, the conventional approach is to locate the corresponding position using an indexOf method on the Adapter. However, this approach encounters a roadblock as the Adapter doesn't provide such a method.
To overcome this challenge, a more suitable approach is to utilize the ArrayAdapter's getPosition method. This method, when paired with a suitable ArrayAdapter, enables the identification of the position associated with a specific value.
Consider a scenario where the Spinner named mSpinner contains a value of "some value". To locate and compare its position, follow these steps:
Create an ArrayAdapter from the resource file R.array.select_state:
<code class="java">ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);</code>
Set the Spinner's Adapter and DropDownViewResource:
<code class="java">adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinner.setAdapter(adapter);</code>
Next, if the value to be compared (compareValue) is not null:
<code class="java">if (compareValue != null) { int spinnerPosition = adapter.getPosition(compareValue); mSpinner.setSelection(spinnerPosition); }</code>
By employing this approach, the Spinner's selection can be accurately set based on the value stored in the database, providing a seamless user experience during view updates.
The above is the detailed content of How to Set a Spinner's Selection by Value, Not Position in Android?. For more information, please follow other related articles on the PHP Chinese website!