【问题标题】:Android Databinding: how to get field value of kotlin enum class?Android数据绑定:如何获取kotlin枚举类的字段值?
【发布时间】:2019-11-14 04:49:17
【问题描述】:

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

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

我想将 XML 中的字段值与数据绑定一起使用。我的 ViewModel 提供了一个 ObservableField<MyEnum>,它应该通过数据绑定在 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>

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

【问题讨论】:

  • 你确定你没有使用@={}而不是@{}作为数据绑定表达式吗?
  • @CommonsWare 是的,刚刚再次检查:我使用@{} 语法
  • 这很奇怪,因为我不知道为什么在这种情况下数据绑定需要一个 setter。
  • 这篇文章中的错字“andoid:text”是吗?
  • 是的,这只是帖子中的错字

标签: android kotlin android-databinding


【解决方案1】:

迟到了,但你试过用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>

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2023-03-09
    相关资源
    最近更新 更多