DylanCaiCoding/ViewBindingKTX

自定义View使用不显示

jiqianwen opened this issue · 2 comments

QQ截图20210812121158
QQ截图20210812121256
如图,使用by binding()的 方式直接不显示 ,自己手动初始化然后addView的方式就可以显示,请问下是什么原因导致的

很抱歉给你造成了困惑,因为使用委托不会立即执行代码,所以即使把 binding 对象声明了也没有填充布局,在调用了 binding 对象才会执行代码把布局填充进去。

个人增加了个 inflate() 方法,用 = 号调用而并非 by 关键字,就会立即把布局填充了。Wiki 文档的示例也进行了更新,如下所示:

class CustomView(context: Context, attrs: AttributeSet? = null) :
  ConstraintLayout(context, attrs) {

  private val binding = inflate<LayoutCustomViewBinding>()
  // private val binding = inflate(LayoutCustomViewBinding::inflate)

  private val childBinding: LayoutChildBinding by binding(attachToParent = false)
  // private val childBinding by binding(LayoutChildBinding::inflate, attachToParent = false)

  init {
    binding.container.addView(childBinding.root)
  }
}

升级到 1.2.4 版本就可以使用了。

很抱歉给你造成了困惑,因为使用委托不会立即执行代码,所以即使把 binding 对象声明了也没有填充布局,在调用了 binding 对象才会执行代码把布局填充进去。

个人增加了个 inflate() 方法,用 = 号调用而并非 by 关键字,就会立即把布局填充了。Wiki 文档的示例也进行了更新,如下所示:

class CustomView(context: Context, attrs: AttributeSet? = null) :
  ConstraintLayout(context, attrs) {

  private val binding = inflate<LayoutCustomViewBinding>()
  // private val binding = inflate(LayoutCustomViewBinding::inflate)

  private val childBinding: LayoutChildBinding by binding(attachToParent = false)
  // private val childBinding by binding(LayoutChildBinding::inflate, attachToParent = false)

  init {
    binding.container.addView(childBinding.root)
  }
}

升级到 1.2.4 版本就可以使用了。

已解决,谢谢