如何在微调器

时间:2018-03-27 08:59:21

标签: android kotlin android-spinner

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.
    }
}}

等于&#34;提示&#34;在Edittext中,我需要一个Spinner中的默认文本。

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:-1)

使用下面的代码设置微调器控件提示值。

 class SpinerActivity :AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.spiner)
        setSpinner()
    }

    private fun setSpinner() {
        val mySpinner:Spinner=findViewById(R.id.mySpinner)
        val myStrings = arrayOf("Select Item","One", "Two" , "Three", "Four")
        var adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, myStrings)
        mySpinner.adapter=adapter
        mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            }
        }

    }
}