Sets a spinner (drop-down/select box) selection to the given selection. - Android User Interface

Android examples for User Interface:Spinner

Description

Sets a spinner (drop-down/select box) selection to the given selection.

Demo Code


//package com.java2s;

import android.view.View;

import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class Main {
    /**//from   w w  w  .j av  a  2s.  com
     * Sets a spinner (drop-down/select box) selection to the given selection.
     * @param rootView view containing the specified spinner
     * @param spinnerId e.g R.id.district_spinner
     * @param selection value to set as the spinner's current selection.
     */
    public static void setSelectedValue(View rootView, int spinnerId,
            String selection) {
        if (selection != null) {
            Spinner spinner = (Spinner) rootView.findViewById(spinnerId);
            SpinnerAdapter adapter = spinner.getAdapter();
            for (int i = 0; i < adapter.getCount(); i++) {
                String option = adapter.getItem(i).toString();
                if (selection.equals(option)) {
                    spinner.setSelection(i);
                    return;
                }
            }
        }
    }
}

Related Tutorials