Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-10-31 17:30:02
Original
798 people have browsed it

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);
}
Copy after login

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);
    Copy after login
  3. Set the ArrayAdapter as the Adapter for your Spinner:

    mSpinner.setAdapter(adapter);
    Copy after login
  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);
    }
    Copy after login

    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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!