如何使用视图绑定在 Kotlin 中正确地膨胀视图

How to inflate a view properly in Kotlin with View Binding

我创建了一个自定义视图:

class CustomView(context: Context, attrs: AttributeSet?) : View(context, attrs) {

   val textView: TextView
   val button: Button
   
    init {
        ViewCustomBinding.inflate(LayoutInflater.from(context)).apply {
            this.textView = textView
            this.button = button
        }
    }

这适用于具有 TextViewButton 的自定义视图。但是,当它在任何布局中作为视图膨胀时,我看不到视图被膨胀。我想知道实际上在屏幕上夸大此视图的代码中缺少什么?

您从未将扩充的视图添加到层​​次结构中。您可以添加

addView(binding.root)

或在 inflate 方法中将您的视图作为父级传递。


编辑

我刚刚注意到您的自定义视图继承自 View class,它不能作为其他视图的父视图。您应该使用 ViewGroup.

的一些子 class