gpt4 book ai didi

Android 数据绑定(bind) : how to get field value of kotlin enum class?

转载 作者:行者123 更新时间:2023-12-04 23:51:05 25 4
gpt4 key购买 nike

我有一个包含两个字段的枚举类:

enum class MyEnum(val text1: String, val text2: String) {
A("a1", "a2"),
B("b1", "b2")
}

我想在 XML 中使用该字段值与数据绑定(bind)。我的 ViewModel 提供了 ObservableField<MyEnum>应该通过数据绑定(bind)在 XML 中使用:
class MyViewModel() : ViewModel() {
val myEnum = ObservableField<MyEnum>(MyEnum.A)
}

我尝试读取 XML 中的字段值

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

<import type="com.example.MyEnum" />

<variable
name="vm"
type="com.example.MyViewModel" />
</data>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="@{vm.myEnum.text1}"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</FrameLayout>
</layout>

但我得到以下异常:
找不到带有参数字符串的属性“文本”的 setter

最佳答案

迟到了,但您是否尝试过使用 BindingAdapter

@JvmStatic
@BindingAdapter("yourTitleText")
fun fetchYourTitleText(view: TextView, type: MyEnum) {
view.apply {
text = when (type) {
MyEnum.A -> "Your value for A"
MyEnum.B -> "Your value for B"
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
<import type="com.example.MyEnum" />
<variable
name="vm"
type="com.example.MyViewModel" />
</data>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
app:yourTitleText="@{vm.myEnum}"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</FrameLayout>
</layout>

关于Android 数据绑定(bind) : how to get field value of kotlin enum class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56871088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com