【问题标题】:View Binding with 2 possible layouts, assign binding variable to 2 generated binding classes查看具有 2 种可能布局的绑定,将绑定变量分配给 2 个生成的绑定类
【发布时间】:2021-02-15 19:35:39
【问题描述】:

所需功能:

我有一个 Activity,它有一个从后端接收到的值,表示使用两种布局之一。让我们将此值称为 layoutType,并在下面的示例代码中为简单起见假设我们不关心如何分配它。因此,我有两个布局 xml 文件,我们称它们为 layout1.xml & layout2.xml。

实施: 我想使用View Binding。我创建了一个 ViewBinding 类型的变量,并尝试为其分配 Layout1Binding 或 Layout2Binding。这个逻辑在伪代码中的总结是这样的:

 private ViewBinding binding;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     if(layoutType == 1){
         binding = Layout1Binding.inflate(getLayoutInflater());
     } else {
         binding = Layout2Binding.inflate(getLayoutInflater());
     }
     setContentView(binding.getRoot());
 }

结果:当然,这不起作用,变量 binding 似乎没有可以引用的内部子级。另外,当然如果我将变量的类型转换为 Layout1Binding 并且 layoutType 等于 1,那么我可以正确使用它。如果我使用 Layout2Binding 并且 layoutType 不等于 1 也是如此。所有这些都有意义,因为 ViewBinding 只是由生成的类 Layout1Binding 实现的接口em> & Layout2Binding.

问题:我怎样才能通过只使用一个可以分配给两个不同生成类的绑定变量来实现上述期望的行为?有没有其他替代方法?

【问题讨论】:

  • 您必须编写一个适配器来包装和接受两种绑定类型,同时公开“通用”字段,或者创建一个具有不同绑定类型的通用活动/片段。
  • @Pawel 您能否提供一个相关的代码/伪代码示例来演示此逻辑?我没有适配器,所以我对您的第二个建议更感兴趣。

标签: java android android-layout android-viewbinding


【解决方案1】:

这是我如何将适配器用于使用三种布局的自定义视图的示例。 在我的例子中,不同布局文件中的大多数视图都有共同的 ID。

定义你的绑定适配器类

class MyCustomViewBindingAdapter(
    b1: Layout1Binding?,
    b2: Layout2Binding?,
    b3: Layout3Binding?
) {

    val text =
        b1?.myTextView
            ?: b2?.myTextView
            ?: b3?.myTextView

    val badgeText = b3?.myBadgeTextView
}

创建绑定变量

private lateinit var binding: MyCustomViewBindingAdapter

创建获取绑定适配器的方法

private fun getBinding(layoutType: Int): MyCustomViewBindingAdapter {
    val inflater = LayoutInflater.from(context)

    return when(layoutType) {
        TEXT_ONLY -> {
            val textBinding = Layout1Binding.inflate(inflater, this, true)
            MyCustomViewBindingAdapter(textBinding, null, null)
        }
        IMAGE_AND_TEXT -> {
            val imageTextBinding = Layout2Binding.inflate(inflater, this, true)
            MyCustomViewBindingAdapter(null, imageTextBinding, null)
        }
        TEXT_AND_BADGE -> {
            val textBadgeBinding = Layout3Binding.inflate(inflater, this, true)
            MyCustomViewBindingAdapter(null, null, textBadgeBinding)
        }
        else -> throw IllegalArgumentException("Invalid view type")
    }
}

使用前一定要初始化绑定

binding = getBinding(layoutType)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多