Android 将一个类绑定到两个布局?
在我的应用程序中,我有一个Android 将一个类绑定到两个布局?,android,android-layout,android-databinding,Android,Android Layout,Android Databinding,在我的应用程序中,我有一个产品类,它以两种不同的方式显示:一张包含所有信息的普通卡和一张只显示其部分数据的小卡 因此,我有两种布局:product\u card.xml和product\u card\u small.xml 现在,我可以将这两个布局绑定到同一个产品类吗? 两种布局都有以下特点: <data> <import type="com.MyTest.android.Models.Product"/> <variable name="produ
产品
类,它以两种不同的方式显示:一张包含所有信息的普通卡和一张只显示其部分数据的小卡
因此,我有两种布局:product\u card.xml
和product\u card\u small.xml
现在,我可以将这两个布局绑定到同一个产品类吗?
两种布局都有以下特点:
<data>
<import type="com.MyTest.android.Models.Product"/>
<variable name="product" type="Product"/>
</data>
我有一个productsAdapter
,它选择了一种布局。但是,当我想在其viewHolder中同时使用ProductCardBinding
和ProductCardSmallBinding
时,只能识别其中一个(ProductCardBinding
)。另一个问题无法解决
我想知道这是否可能,如果可能,为什么它只能解决其中一个问题?也许你可以这样做。我从未使用过它
<data class=".Item1">
<import type="com.MyTest.android.Models.Product"/>
<variable name="product" type="Product"/>
</data>
<data class=".Item2">
<import type="com.MyTest.android.Models.Product"/>
<variable name="product" type="Product"/>
</data>
我也有同样的问题。由于一个XML只能绑定到一个
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)
我认为这不是一个好的解决方案,但这至少可以解决它。:) 不确定这是否有帮助,您是否检查了文档中的“包含”部分@Yazan,我对数据绑定没有任何问题,只绑定一个布局。问题是两个布局绑定到一个类…好的,所以它们不会同时显示,很抱歉我误解了你的问题,请添加适配器代码。这是可能的。看起来你做错了什么。