android - 将一个类绑定(bind)到两个布局?

标签 android android-layout android-databinding

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

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

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

两种布局都有这个:

<data>
    <import type="com.MyTest.android.Models.Product"/>
    <variable name="product" type="Product"/>
</data>

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

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

最佳答案

我也有同样的问题。由于一个 XML 只能绑定(bind)到一个 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)

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

关于android - 将一个类绑定(bind)到两个布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855868/

相关文章:

android - 在 onitemclick android 中设置微调项的选定值

android - 在android中修剪/剪切视频文件

android - 我无法设置 Android 数据绑定(bind)

android - 通用@BindingConversion 不起作用

Android 线性布局 : Layout inside a Layout

android - android中膨胀布局的数据绑定(bind)不会刷新

android - 无法解析 ':app@debug/compileClasspath' : Could not resolve project :react-native-firebase 的依赖关系

android - Flutter中有WebView吗?

javascript - 使用 JavaScript 在 Android (Chrome) 上使用计时器播放声音

android - Android 中的自定义形状按钮