android - 如何在 XML 的微调器中添加提示

标签 android xml spinner android-spinner

我正在尝试在微调器小部件中添加提示,因为在 EditText 中没有提示选项,我想将性别显示为提示,单击时它必须仅显示男性和女性不是提示。

如何仅使用 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>

最佳答案

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

@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;
    }
}

并将第一项设置为灰色。

@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;
}

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

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

详情请引用以下链接。

How to add a hint to Spinner in Android

关于android - 如何在 XML 的微调器中添加提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019941/

相关文章:

java - 安卓 : Text stretches to button?

android - 使用LinearLayout将按钮放在屏幕底部?

android - OpenCV HoughCircles cvRound

android - 使用MediaPlayer播放声音

java - 如何使用 DOM API 访问 XML 节点的值

android - 更改单选按钮的文本格式并获取所有国家/地区的列表并将其放入微调器 Android

android - 如何在带有 php mysql 的 android 中的一个 Activity 中使用两个微调器

android - 如何修复构建工具 (22.0.0/1) 依赖性问题

安卓:Process.myTid() VS Thread.currentThread().getId()

android - 微调器看起来不合适