【问题标题】:Set text of spinner before item is selected在选择项目之前设置微调器的文本
【发布时间】:2012-06-07 16:25:07
【问题描述】:

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

我该怎么做?

【问题讨论】:

标签: android spinner oncreate settext


【解决方案1】:

您可以通过以下两种方式之一来做到这一点。

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

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

编辑

在你的资源中

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

在你的 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
        }
    }
});

【讨论】:

  • 有没有办法从字符串资源中插入?
  • 是的,只需将其添加为数组资源中的第一个条目即可。我编辑了我的答案以提供一个例子。
  • +1,好技巧,但如果我们可以从选择的一项中删除单选按钮,那就太好了。
  • @SahilMahajanMj 不在下拉列表中怎么样?检查this answer 的方法。
【解决方案2】:

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

例子:

<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" 
/> 

【讨论】:

  • 不是 OP 想要的。他希望它在微调器中,而不是作为它的标题。
  • 查看这篇文章,它提供了做你想做的事情的方法。 stackoverflow.com/questions/867518/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
相关资源
最近更新 更多