如何解决数据绑定:如何在一个视图中绑定不同的数据变量
我正在使用 MVVM 设计模式,因此使用本机数据绑定。
是否可以在数据绑定中为一个视图使用多个数据变量?
我的意思是我有一个使用数据绑定的xml布局,我想将它用于多个recyclerview项目。
这是一个 recyclerview 项目的第一个数据模型类:
data class Sample1 (
val name: String,val id: Int
)
这是另一个 recyclerview 项目的第二个:
data class Sample2 (
val name: String,val type: String
)
这是在两个 recyclerview 中使用的 xml 代码:
<layout>
<data class="SampleDataBinding">
<variable
name="Sample1"
type="model.Sample1" />
<variable
name="Sample2"
type="model.Sample2" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="@{Sample1.component1()}" // this line may be different in another recyclerview item
android:textColor="@color/black" />
</LinearLayout>
我不是说两个字符串的连接。我的意思是 TextView 在第一个 recyclerview 项目和第二个项目中可能不同。
如果可能,我该怎么做?
提前致谢
解决方法
您可以使用接口来实现它,并且您的 XML/数据绑定将与该接口一起使用。例如,您需要该 xml 中的标题,您可以创建一个接口 (SampleRecyclerItem
),其实现者必须提供一个 title: String
。
interface SampleRecyclerItem{
val title: String
}
data class Sample1 (
val name: String,val id: Int
) : SampleRecyclerItem {
override val title get() = name // either using a getter
}
data class Sample2 (
val name: String,val type: String
) : SampleRecyclerItem {
override val title by this::name // or using delegation (easier for vars for not providing setter and getter)
}
然后,您的 XML 可以使用此接口而不是直接使用数据类
<layout>
<data class="SampleDataBinding">
<variable
name="sample"
type="model.SampleRecyclerItem" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="@{sample.title}"
android:textColor="@color/black" />
</LinearLayout>
,
这可以通过 elvis 运算符实现,但您需要比较一些东西以选择所需的值。如果只是关于文字。在适配器类中提供逻辑并将文本传递给数据绑定而不是许多无用的对象。如果您需要更复杂的解决方案,则需要使用不同的视图类型和 ViewHolder
。 Example link
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。