Android 在选择项目之前设置微调器的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10867039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:17:10  来源:igfitidea点击:

Set text of spinner before item is selected

androidspinneroncreatesettext

提问by JohnD

I have a spinner with three items and I use an XML string-array resource to feed it. When you open an activity the spinner normally shows the first item that's in the array list. I'd like to change that and show the text "Select one" in the spinner, before an item is selected.

我有一个包含三个项目的微调器,我使用 XML 字符串数组资源来提供它。当您打开一个活动时,微调器通常会显示数组列表中的第一个项目。我想改变它并在选择项目之前在微调器中显示文本“选择一个”。

How can I do that?

我怎样才能做到这一点?

回答by Barak

You can do that one of two ways.

您可以通过以下两种方式之一执行此操作。

1) Add "Select One" as the first item in your xml and code your listener to ignore that as a selection.

1) 将“Select One”添加为 xml 中的第一项,并对您的侦听器进行编码以将其作为选择忽略。

2) Create a custom adapter to insert it as the first line,

2)创建一个自定义适配器将其作为第一行插入,

EDIT

编辑

In your resources

在您的资源中

<string-array name="listarray">
    <item>Select One</item>
    <item>Item One</item>
    <item>Item Two</item>
    <item>Item Three</item>
</string-array>

In your onItemSelected Listener:

在您的 onItemSelected 侦听器中:

spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if (pos == 0) {
        }else {
            // Your code to process the selection
        }
    }
});

回答by 113408

To set a default text for the spinner you have to use android:prompt=@string/SelectOnefor your spinner Where SelectOne is defined in your string.xml .

要为微调器设置默认文本,您必须android:prompt=@string/SelectOne为微调器使用SelectOne 在 string.xml 中定义的地方。

Example :

例子 :

<Spinner android:id="@+id/spinnerTest"  
 android:layout_marginLeft="50px"
 android:layout_width="fill_parent"                  
 android:drawSelectorOnTop="true"
 android:layout_marginTop="5dip"
 android:prompt="@string/SelectOne"
 android:layout_marginRight="30px"
 android:layout_height="35px" 
/>