如何在微调器中添加提示

eye*_*ler 6 android android-spinner kotlin

微调器的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" />`
Run Code Online (Sandbox Code Playgroud)

.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.
    }
}}
Run Code Online (Sandbox Code Playgroud)

等于Edittext中的“提示”选项,我需要Spinner中的默认文本。

Vir*_*hit 6

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

val myStrings = arrayOf("Select","One", "Two" , "Three", "Four")
Run Code Online (Sandbox Code Playgroud)

现在,为微调器定义自定义适配器,并禁用如下第一项。

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以如下更改颜色

@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;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:-

在微调器中添加提示