13

通过数据绑定,我们有一个 DataBindingUtil 类,它有一个可以处理任何布局 id 的 inflate 方法:

binding = DataBindingUtil.inflate<ViewDataBinding>(inflater, layoutId, parent, false)

使用视图绑定,似乎没有 ViewBindingUtil 类。Inflate 方法旨在在具体绑定类型上调用。但是,如果您不提前知道具体的绑定类型怎么办?一种解决方案是在 layoutId 上运行 when 语句:

binding = when (layoutId) {
    R.id.layout1 -> Layout1Binding.inflate(...)
    R.id.layout2 -> Layout2Binding.inflate(...)
    R.id.layout3 -> Layout3Binding.inflate(...)
    etc...
}

但与单行数据绑定相比,这是很多代码。有没有更好的办法?我找到了这个 3rd 方库,但它看起来像使用反射:https ://github.com/matsudamper/ViewBindingUtil

4

0 回答 0