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

查看:31
本文介绍了如何在 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 来完成

How it can be Done Only Using XML

微调器的 XML 代码.

XML code of spinner.

  <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();
    }
}

详情请参考以下链接.

如何在 Android 中向 Spinner 添加提示

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

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