View Binding随v3.6一起发布。
文档:https://developer.android.com/topic/libraries/view-binding
我的问题是,如何将视图绑定与自定义视图一起使用。 google docus仅显示了用例显示的活动和片段。
我尝试过,但是什么也没显示。
LayoutInflater inflater = LayoutInflater.from(getContext());
然后,我用了这个,但是再一次,没有运气。
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
我猜,也许我没有针对我的视图设置正确的布局填充器,但不确定。
要使用视图绑定,您需要使用生成的绑定类而不是LayoutInflater
,例如,如果布局名称是result_profile.xml
,则需要使用ResultProfileBinding
作为:
class CustomView @kotlin.jvm.JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private lateinit var binding: ResultProfileBinding
init { // inflate binding and add as view
binding = ResultProfileBinding.inflate(LayoutInflater.from(context))
addView(binding.root)
}
}
result_profile.xml
-> ResultProfileBinding
(版面名称,附加Binding
)增加绑定
ResultProfileBinding.inflate(LayoutInflater.from(context))
使用addView
将层次结构中的视图添加为:
addView(binding.root)
注意:如果您是从ConstraintLayout
(是父类)扩展而来,请使用constraint set
如果您尝试将视图绑定与根视图一起使用,这对我有用:
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private lateinit var binding: CustomViewBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = CustomViewBinding.bind(this)
}
}