如何在 android 布局数据绑定中指定 class(不是字符串)

how to specify class (not string) in android layout data binding

我为采用自定义对象的 ImageView 添加了这样的新绑定规则:

@BindingAdapter({"custDrawable"})
public static void setCustDrawable(@NonNull ImageView view, HexDrawableModel model) {
    view.setImageDrawable(new HexDrawable(model));
}

其中 HexDrawable 扩展 Drawable,并且

data class HexDrawable(val text: String, val color: Color)

所以...我不确定如何在我的布局文件中使用此绑定适配器,因为它需要 class 而不是字符串。请让我知道使用这个绑定适配器(如果可能的话)。

布局中XML:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    custDrawable=??? />

使用app:custDrawable={$variable}

在布局的 data 部分定义变量并将其绑定到相应的 java 文件

我认为你应该这样声明它们

@BindingAdapter("custDrawable")
public static void setCustDrawable(@NonNull ImageView view, HexDrawableModel model) {
    view.setImageDrawable(new HexDrawable(model));
}

并像这样使用它们

<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>
       ...
    </data>

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:custDrawable="@{yourVariableHere}/>

</layout>