首页 > 解决方案 > 在数据绑定属性中传递类类型

问题描述

我们可以在android数据绑定中做这样的事情吗

itemType="@{MyClass::class}"

用于绑定适配器

@BindingAdapter(value = ["itemType"])
fun <T> func(
view: View,
itemType: Class<T>,
) {}

标签: androidkotlindata-bindingandroid-binding-adapter

解决方案


不,您不会通过课程,而是会通过数据对象。这是示例:

<ListView
            android:id="@+id/bookList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:items="@{viewmodel.items}" />

这是用于此的绑定适配器:

@BindingAdapter("app:items")
@JvmStatic
fun setItems(listView: ListView, items: List<Book>) {
    with(listView.adapter as BookListAdapter) {
        replaceData(items)
    }
}

鉴于这viewmodel.items是 LiveData,更新它会自动更新列表视图。


推荐阅读