Home >Java >javaTutorial >How to Programmatically Set the Selected Item in an Android Spinner by Value?

How to Programmatically Set the Selected Item in an Android Spinner by Value?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 17:30:02893browse

How to Programmatically Set the Selected Item in an Android Spinner by Value?

Setting Selected Item of Spinner by Value

When updating a view, you may encounter the need to preselect a value stored in the database for a Spinner. Initially, you might attempt a solution such as:

void setSpinner(String value)
{
    int pos = getSpinnerField().getAdapter().indexOf(value);
    getSpinnerField().setSelection(pos);
}

However, this approach encounters a roadblock as the Adapter interface does not provide an indexOf method.

Solution

To find and compare the position of a specific value within your Spinner, follow these steps:

  1. Define a comparison value, for example: String compareValue = "some value".
  2. Create an ArrayAdapter using the required resource:

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
  3. Set the ArrayAdapter as the Adapter for your Spinner:

    mSpinner.setAdapter(adapter);
  4. Use the getPosition method to determine the position of your comparison value within the ArrayAdapter:

    if (compareValue != null) {
     int spinnerPosition = adapter.getPosition(compareValue);
     mSpinner.setSelection(spinnerPosition);
    }

    By following these steps, you can effectively preselect a value in a Spinner based on its value rather than its position in the list.

The above is the detailed content of How to Programmatically Set the Selected Item in an Android Spinner by Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn