使用 2 种可能的布局查看绑定,将绑定变量分配给 2 个生成的绑定类

Tha*_*s M 7 java android android-layout android-viewbinding

所需功能:

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

实现: 我想使用View Binding。我创建了一个ViewBinding类型的变量,并尝试为其分配Layout1BindingLayout2Binding。这个逻辑的伪代码总结如下:

 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());
 }
Run Code Online (Sandbox Code Playgroud)

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

问题:如何仅使用一个可以分配给两个不同生成类的绑定变量来实现上述所需的行为?还有其他替代方法吗?

Mar*_*ark 7

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

定义您的绑定适配器类

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

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

    val badgeText = b3?.myBadgeTextView
}
Run Code Online (Sandbox Code Playgroud)

创建绑定变量

private lateinit var binding: MyCustomViewBindingAdapter
Run Code Online (Sandbox Code Playgroud)

创建一个方法来获取绑定适配器

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")
    }
}
Run Code Online (Sandbox Code Playgroud)

使用前请务必初始化绑定

binding = getBinding(layoutType)
Run Code Online (Sandbox Code Playgroud)