在自定义 ViewGroup 中使用 ViewBinding 需要进行以下步骤:

  1. 在 build.gradle 中添加 ViewBinding 的依赖:
android {
    ...
    viewBinding {
        enabled = true
    }
}
  1. 在自定义 ViewGroup 中创建一个 ViewBinding 对象:
class MyCustomViewGroup @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    private val binding: MyViewGroupBinding = MyViewGroupBinding.inflate(LayoutInflater.from(context), this, true)

    ...
}

其中,MyViewGroupBinding 是根据 XML 布局文件生成的绑定类。

  1. 在 XML 布局文件中声明自定义 ViewGroup 时,使用 <merge> 标签作为根布局:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text='Hello World!' /> 
</merge>

这样就可以通过 ViewBinding 的方式绑定自定义 ViewGroup 中的视图了。

ViewBinding 自定义 ViewGroup 视图绑定指南

原文地址: https://www.cveoy.top/t/topic/mLlJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录