web-dev-qa-db-fra.com

Afficher la valeur par défaut dans Spinner dans android

Je veux montrer un menu déroulant pour la sélection du sexe. J'ai passé un tableau de chaînes comme

String arr[]=new String[]{"male","female"};

mais le problème est qu'il montre la sélection par défaut avec la valeur de "male" et je veux montrer "Gender" comme valeur par défaut. Si je passe "Sexe" dans le tableau à la position 0, il est également visible dans la liste déroulante. Je veux juste "Sexe" comme indice mais il ne faut pas le montrer dans la liste déroulante.

Quelqu'un peut-il me dire comment je peux faire cela? Merci d'avance.

33
rahul

J'ai trouvé une solution en étendant ArrayAdapter et en redéfinissant la méthode getView.

import Android.content.Context;
import Android.support.annotation.NonNull;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.ArrayAdapter;
import Android.widget.Spinner;
import Android.widget.TextView;

/**
 * A SpinnerAdapter which does not show the value of the initial selection initially,
 * but an initialText.
 * To use the spinner with initial selection instead call notifyDataSetChanged().
 */
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {

    private Context context;
    private int resource;

    private boolean initialTextWasShown = false;
    private String initialText = "Please select";

    /**
     * Constructor
     *
     * @param context The current context.
     * @param resource The resource ID for a layout file containing a TextView to use when
     *                 instantiating views.
     * @param objects The objects to represent in the ListView.
     */
    public SpinnerAdapterWithInitialText(@NonNull Context context, int resource, @NonNull T[] objects) {
        super(context, resource, objects);
        this.context = context;
        this.resource = resource;
    }

    /**
     * Returns whether the user has selected a spinner item, or if still the initial text is shown.
     * @param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
     * @return true if the user has selected a spinner item, false if not.
     */
    public boolean selectionMade(Spinner spinner) {
        return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
    }

    /**
     * Returns a TextView with the initialText the first time getView is called.
     * So the Spinner has an initialText which does not represent the selected item.
     * To use the spinner with initial selection instead call notifyDataSetChanged(),
     * after assigning the SpinnerAdapterWithInitialText.
     */
    @Override
    public View getView(int position, View recycle, ViewGroup container) {
        if(initialTextWasShown) {
            return super.getView(position, recycle, container);
        } else {
            initialTextWasShown = true;
            LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(resource, container, false);

            ((TextView) view).setText(initialText);

            return view;
        }
    }
}

Ce que Android fait lors de l’initialisation de Spinner, appelle getView pour l’élément sélectionné avant d’appeler getView pour tous les éléments de T[] objects. Le SpinnerAdapterWithInitialText renvoie un TextView avec le initialText, lors de son premier appel. Toutes les autres fois, il appelle super.getView qui est la méthode getView de ArrayAdapter qui est appelée si vous utilisez le Spinner normalement.

Pour savoir si l'utilisateur a sélectionné un élément de spinner ou si le spinner affiche toujours le initialText, appelez selectionMade et remettez le spinner auquel l'adaptateur est affecté.

2
pfaehlfd

Spinner ne supporte pas Hint, je vous recommande de créer un adaptateur spinner personnalisé.

vérifiez ce lien: https://stackoverflow.com/a/13878692/1725748

0
OWZY