How to set selected item of Spinner by value, not by position?
To set the selected item of a Spinner
by value (not by position) in Android, you can use the setSelection()
method of the Spinner
class and pass it the index of the item that you want to select.
To find the index of an item by its value, you can use the indexOf()
method of the Spinner
's Adapter
.
Here is an example of how you can set the selected item of a Spinner
by value in Android:
Spinner spinner = findViewById(R.id.spinner);
String value = "item2"; // value to select
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
int position = adapter.getPosition(value); // get position of value
spinner.setSelection(position); // set selected item by position
In this example, the Spinner
is populated with an array of items from the R.array.items
resource. The setSelection()
method is used to set the selected item by the index returned by the getPosition()
method.
I hope this helps! Let me know if you have any questions.