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.
Android's Spinner natively supports selection only by position using the setSelection(int position) method. To select an item by its value, you must first find the corresponding position in the adapter and then pass that index to setSelection().
Here is an example of how to locate the position of a value and set it as the selected item:
Spinner spinner = findViewById(R.id.spinner);
String valueToSelect = "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);
// Find the position of the value
int position = -1;
for (int i = 0; i < adapter.getCount(); i++) {
if (String.valueOf(adapter.getItem(i)).equals(valueToSelect)) {
position = i;
break;
}
}
// Set the selected item by the found position
if (position != -1) {
spinner.setSelection(position);
}In this example, the Spinner is populated with an array of items from the R.array.items resource. We iterate through the adapter to find the index matching valueToSelect, then use setSelection() to apply it.