在Android中的Spinner中显示默认值

39

我想展示一个下拉框用于选择性别。我传递了一个字符串数组作为参数。

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

但问题是它显示了默认选择,值为"male",我想将"Gender"显示为默认值。如果我在数组中传递"Gender"到位置0,则它也会在下拉列表中可见。我只想要"Gender"作为提示,但不应在下拉列表中显示。

如何实现?


3
请查看这里提出了同样的问题:https://dev59.com/CHNA5IYBdhLWcg3wrf83 - Nargis
请问您能否截取一张您所需设计的屏幕截图?谢谢。 - Jarvis
4个回答

67
Spinner sp = (Spinner)findViewById(R.id.spinner); 
sp.setSelection(pos);

这里的pos是整数(你的数组项位置)

如果数组如下,则pos = 0;

String str[] = new String{"Select Gender","male", "female" };

然后在onItemSelected中

@Override
    public void onItemSelected(AdapterView<?> main, View view, int position,
            long Id) {

        if(position > 0){
          // get spinner value
        }else{
          // show toast select gender
        }

    }

3

我通过扩展ArrayAdapter并重写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;
        }
    }
}

Spinner在初始化时会先调用所选项目的getView方法,然后才会调用T[]对象中所有项目的getView方法。 SpinnerAdapterWithInitialText会在第一次调用时返回一个带有initialText的TextView。 其他情况下,它会调用ArrayAdapter的getView方法(如果你正常使用Spinner),即调用super.getView方法。 要确定用户是否选择了Spinner项目或Spinner是否仍显示initialText,请调用selectionMade并将其传递给适配器所分配的Spinner。

这是一个不错的解决方案,但你必须为0位置选择添加验证。如果spinner保持在0位置,它不会将其视为选择,因此它不会更改默认值。 - htafoya

1

Spinner不支持提示?那“promt”呢? - Aleksandr

-7

请尝试以下:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接