如何在XML的微调器中添加提示 [英] How to add a Hint in spinner in XML

查看:70
本文介绍了如何在XML的微调器中添加提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在微调器窗口小部件中添加提示,因为没有像EditText中所示的提示选项,我想将性别显示为提示,并且单击时必须仅显示男性和女性,而不显示提示.

I am trying to add a Hint in the spinner widget as there is no option of Hint as in EditText, I want to show Gender as a Hint and when clicked it must show only Male and Female not the hint.

仅使用XML即可完成

微调器的XML代码.

  <Spinner
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/spinner1"
      android:entries="@array/gender"
      android:layout_marginTop="10dp"
      android:layout_marginLeft="25dp"
      android:layout_marginRight="25dp"
      android:layout_gravity="center_horizontal" />

微调器的字符串数组

<string-array name="gender">
     <item>Male</item>
     <item>Female</item>
</string-array>

推荐答案

在适配器中,您可以将第一项设置为禁用.下面是示例代码

In the adapter you can set the first item as disabled. Below is the sample code

@Override
public boolean isEnabled(int position) {
    if (position == 0) {
        // Disable the first item from Spinner
        // First item will be use for hint
        return false;
    } else {
        return true;
    }
}

并将第一项设置为灰色.

And set the first item to grey color.

@Override
public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {
    View view = super.getDropDownView(position, convertView, parent);
    TextView tv = (TextView) view;
    if (position == 0) {
        // Set the hint text color gray
        tv.setTextColor(Color.GRAY);
    } else {
        tv.setTextColor(Color.BLACK);
    }
    return view;
}

如果用户选择了第一项,则什么也不做.

And if the user selects the first item then do nothing.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedItemText = (String) parent.getItemAtPosition(position);
    // If user change the default selection
    // First item is disable and it is used for hint
    if (position > 0) {
        // Notify the selected item text
        Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
    }
}

请参阅下面的链接以获取详细信息.

Refer the below link for detail.

如何在Android的Spinner中添加提示

这篇关于如何在XML的微调器中添加提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆