在我的应用程序中,我有一个 Product
类,它以两种不同的方式显示:包含所有信息的普通卡片和仅显示部分数据的小卡片。
因此,我有两个布局:product_card.xml
和 product_card_small.xml
。
现在,我可以将这两个布局绑定(bind)到同一个 Product
类吗?
两种布局都有这个:
<data>
<import type="com.MyTest.android.Models.Product"/>
<variable name="product" type="Product"/>
</data>
我有一个productsAdapter
,它选择其中一种布局。但是,当我想在其 viewHolder 中同时使用 ProductCardBinding
和 ProductCardSmallBinding
时,只能识别其中之一 (ProductCardBinding
)。另一个无法解决。
我想知道是否可能,如果可以,为什么它只解决其中一个?
最佳答案
我也有同样的问题。由于一个 XML 只能绑定(bind)到一个 ViewDataBinding
,你基本上不能这样做。我当前的解决方案是使用代理类。在你的情况下,如果 ProductCardBinding
和ProductCardSmallBinding
两者都有一个 TextView
和ImageView
,然后ProductCardBindingProxy
看起来像这样:
class ProductCardBindingProxy {
val someText: TextView
val someImage: ImageView
val viewDataBinding: ViewDataBinding
constructor(productCardBinding: ProductCardBinding) {
viewDataBinding = productCardBinding
someImage = productCardBinding.image
someText = productCardBinding.text
}
constructor(productCardSmallBinding: ProductCardSmallBinding) {
viewDataBinding = productCardSmallBinding
someImage = productCardSmallBinding.image
someText = productCardSmallBinding.text
}
}
那么你可以在 onCreateViewHolder
中使用它
val proxy = ProductCardBindingProxy(viewBinder)
ProductCardViewHolder(proxy)
我认为这不是一个好的解决方案,但这至少可以解决它。 :)
关于android - 将一个类绑定(bind)到两个布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855868/