通过数据绑定,我们有一个DataBindingUtil类,该类具有一个可处理任何布局ID的inflate方法:
binding = DataBindingUtil.inflate<ViewDataBinding>(inflater, layoutId, parent, false)
使用视图绑定时,似乎没有ViewBindingUtil类。膨胀方法应在具体的绑定类型上调用。但是,如果您不提前知道具体的绑定类型怎么办?一种解决方案是在layoutId上运行when语句:
binding = when (layoutId) {
R.id.layout1 -> Layout1Binding.inflate(...)
R.id.layout2 -> Layout2Binding.inflate(...)
R.id.layout3 -> Layout3Binding.inflate(...)
etc...
}
但是,与一种数据绑定相比,这是很多代码。有没有更好的办法?我找到了这个第三方库,但看起来它使用了反射:https://github.com/matsudamper/ViewBindingUtil