【问题标题】:Make hint for Android spinner using enums使用枚举为 Android 微调器提供提示
【发布时间】:2019-06-11 11:08:15
【问题描述】:

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

你有什么解决方案还在使用适配器中的枚举吗?

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

【问题讨论】:

  • IdentityType 是你的班级吗?可以编辑吗?
  • IdentityType 是我的枚举,包含 DRIVING_LICENSE、ID_CARD 和 PASSPORT 值,我无法编辑它,它包含在域层中

标签: android kotlin android-arrayadapter


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    相关资源
    最近更新 更多