首页 > 解决方案 > 如何在自定义视图上使用视图绑定

问题描述

View Binding 作为 Android Jetpack 的一部分发布

文档:https ://developer.android.com/topic/libraries/view-binding

我的问题是,如何将视图绑定与自定义视图一起使用。Google 文档只有展示的 Activity 和 Fragment。

我试过这个,但什么也没显示。

LayoutInflater inflater = LayoutInflater.from(getContext());

然后,我使用了这个,但又一次,没有运气。

LayoutInflater inflater = (LayoutInflater)
            getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

我想也许我没有针对我的观点选择正确的布局充气器,但不确定。

标签: androidandroid-custom-viewandroid-viewbinding

解决方案


只需通知根,以及是否要附加到它

init { // inflate binding and add as view
    binding = ResultProfileBinding.inflate(LayoutInflater.from(context), this)
}

或者

init { // inflate binding and add as view
    binding = ResultProfileBinding.inflate(LayoutInflater.from(context), this, true)
}

使用哪种膨胀方法取决于 xml 中的根布局类型。


推荐阅读