将一个类绑定到两个布局?

发布时间:2022-09-10 / 作者:清心寡欲
本文介绍了将一个类绑定到两个布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个product类,它以两种不同的方式显示:一个是包含所有信息的普通卡片,另一个是只显示部分ITS数据的小卡片。

因此,我有两个布局:product_card.xmlproduct_card_small.xml

现在,我可以将这两个布局绑定到同一个Product类吗?

两种布局都有:


    
    

我有一个productsAdapter,它选择其中一个布局。但是,当我想在其viewHolder中同时使用ProductCardBindingProductCardSmallBinding时,只能识别其中一个(ProductCardBinding)。另一个无法解析。

我想知道这是否可能,如果可能,为什么它只解决其中一个问题?

推荐答案

我遇到了同样的问题。因为一个XML只能绑定到一个ViewDataBinding,所以基本上不能这样做。我目前的解决方案是使用代理类。在您的示例中,如果ProductCardBindingProductCardSmallBinding都有一个TextViewImageView,则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)

我认为这不是一个好的解决方案,但这至少可以解决它。:)

这篇关于将一个类绑定到两个布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Binding one class to two layouts?


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。