Setting Spinner Selected Item by Value: A Comprehensive Guide
When working with Android's Spinner widget, it may be necessary to preselect an item based on its value rather than its position within the list. To achieve this, the following steps can be taken:
Step 1: Create and Initialize the Spinner with an ArrayAdapter
<code class="java">Spinner mSpinner = (Spinner) findViewById(R.id.my_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.my_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinner.setAdapter(adapter);</code>
Step 2: Retrieve the Value to be Preselected
Assuming the desired value is stored in a variable named preselectedValue, retrieve it as follows:
<code class="java">String preselectedValue = /* Fetch the stored value here */;</code>
Step 3: Search for the Position of the Preselected Value
The position of the preselected value in the Spinner's adapter can be obtained using the getPosition() method of the ArrayAdapter:
<code class="java">int position = adapter.getPosition(preselectedValue);</code>
Step 4: Set the Spinner's Selection
Once the position of the preselected value is known, set the Spinner's selected item using the setSelection() method:
<code class="java">mSpinner.setSelection(position);</code>
Here is a complete code snippet to illustrate the entire process:
<code class="java">String preselectedValue = /* Fetch the stored value here */; Spinner mSpinner = (Spinner) findViewById(R.id.my_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.my_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinner.setAdapter(adapter); if (preselectedValue != null) { int position = adapter.getPosition(preselectedValue); mSpinner.setSelection(position); }</code>
By following these steps, you can easily preselect a value in a Spinner by searching for its position within the underlying adapter.
The above is the detailed content of How to Preselect a Value in an Android Spinner by its Value?. For more information, please follow other related articles on the PHP Chinese website!