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

标签 android kotlin android-spinner

微调器的XML代码:

<Spinner
    android:id="@+id/mySpinner"
    https://stackoverflow.com/questions       
    style="@style/Widget.AppCompat.DropDownItem.Spinner"
    android:layout_width="match_parent"
    android:layout_height="70dp" />`

.kotlin:

val myStrings = arrayOf("One", "Two" , "Three", "Four")
mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, myStrings)
mySpinner.onItemSelectedListener = object : 
AdapterView.OnItemSelectedListener {
    override fun onNothingSelected(parent: AdapterView<*>?) {
        TODO("not implemented") 
        //To change body of created functions use File | Settings | File Templates.
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        TODO("not implemented") 
        //To change body of created functions use File | Settings | File Templates.
    }
}}

与 Edittext 中的“提示”选项相同,我需要 Spinner 中的默认文本。

最佳答案

在微调器中显示提示没有任何默认方式。 为此,您需要在数组中手动​​添加一项,如下所示。

val myStrings = arrayOf("Select","One", "Two" , "Three", "Four")

现在, 为 Spinner 定义自定义适配器并禁用第一项,如下所示。

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

更多信息请访问:-

Add hint in spinner

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

相关文章:

android - 接收器上的 "Exported receiver does not require permission"意味着从系统服务接收

java - 10 秒后运行任务,除非用户按下按钮

java - 在 Android Kotlin 中重新访问应用程序后快速加载启动画面

java - 如何判断我的 Spring boot 应用程序是否处于 Debug模式?

android - 使用 appcompat v21 将 TextView 设置为 Spinner

java - 当我尝试将 Firebase 数据库中的项目包含在其项目列表中时,如何修复微调器不断关闭并重新打开的问题

android - Nexus 5/5x 上不显示微调器下拉箭头

android - 在不同的端口运行多个 react-native 应用程序

Android 在两个分隔线之间水平对齐 TextView

android - 请求定位权限,grantResults为空