簡體   English   中英

Android 數據綁定:如何獲取 kotlin 枚舉類的字段值?

[英]Android Databinding: how to get field value of kotlin enum class?

我有一個包含兩個字段的枚舉類:

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>

但我收到以下異常:找不到帶有參數字符串的屬性“文本”的設置器

遲到了,但您是否嘗試過使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM