使用枚举为Android微调框提示

时间:2019-06-11 11:08:15

标签: android kotlin android-arrayadapter

我找不到解决方案:我想在Spinner上显示提示文本,但设置的适配器仅接受枚举类型(IdentityType枚举),因此无法向其添加字符串(用于提示)< / p>

您还有使用适配器中的枚举的解决方案吗?

private fun initDriverIdentityTypeSpinner() {
    driverIdentityTypeSpinner.adapter = object : ArrayAdapter<IdentityType>(context!!, android.R.layout.simple_spinner_item,IdentityType.values()) {
        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
            (super.getDropDownView(position, convertView, parent) as CheckedTextView).also{
                it.setText(getItem(position)!!.stringRes())
            }
        override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
            (super.getView(position, convertView, parent) as TextView).also {
                it.setText(getItem(position)!!.stringRes())
            }

        override fun isEnabled(position: Int): Boolean = position != 0

    }.also {
        it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    }
}

//IdentityType Extension
@StringRes
fun IdentityType.stringRes(): Int {
    return when(this) {
        IdentityType.DRIVING_LICENSE -> R.string.driving_license
        IdentityType.ID_CARD -> R.string.id_card
        IdentityType.PASSPORT -> R.string.passport
    }
}

1 个答案:

答案 0 :(得分:0)

在Kotlin中,可以将属性放入枚举(在这里称为枚举类)。您可以在构造函数中定义它,如下所示:

enum class IdentityType(val stringResId: Int) {
    DRIVING_LICENSE(R.string.driving_license),
    ID_CARD(R.string.id_card),
    PASSPORT(R.string.passport)
}

然后,您可以像使用它是类的通用属性一样使用它。

val type: IdentityType = ...
val string = getString(type.stringResId)