自定义View使用不显示
jiqianwen opened this issue · 2 comments
jiqianwen commented
DylanCaiCoding commented
很抱歉给你造成了困惑,因为使用委托不会立即执行代码,所以即使把 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 版本就可以使用了。
jiqianwen commented
很抱歉给你造成了困惑,因为使用委托不会立即执行代码,所以即使把 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 版本就可以使用了。
已解决,谢谢