android - 使用枚举为 Android 微调器提供提示
问题描述
我找不到问题的解决方案:我希望在 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
}
}
解决方案
在 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)
推荐阅读
- css - 如何固定通量中一个元素的位置?
- ios - 我的应用在 xcode 11.4 中找不到 sirikit intentdefinition 类
- lda - LDA 模型中 0.3 的相干值
- sql - PLSQL使用数组从表中选择到变量中
- javascript - 如何在不渲染的情况下将 React 组件导出为 pdf
- java - 将数据库中的值添加到 logback 日志消息
- json - Dart/Flutter JSON解析与展示
- php - 在 laravel 中调用未定义的方法 Illuminate\Auth\TokenGuard::attempt()
- php - 基于带有附加功能的下拉列表自动填充字段
- linux - 如何生成一个全新文件的补丁?