[英]Custom Android view has wrong type when inflating from XML
I have a custom view, that extends LinearLayout
:我有一个自定义视图,它扩展了
LinearLayout
:
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {
private val binding = MyCustomViewBinding.inflate(LayoutInflater.from(context), this, true)
// ...
}
And I need to define a custom wrapper (similar to TextInputLayout ), that can include a child MyCustomView
object and has a special logic to inflate it.而且我需要定义一个自定义包装器(类似于TextInputLayout ),它可以包含一个子
MyCustomView
object 并且有一个特殊的逻辑来膨胀它。 So I want to be able to define the views in XML as follows:所以我希望能够在 XML 中定义视图,如下所示:
<com.example.MyCustomWrapper
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.MyCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.example.MyCustomWrapper>
For that purpose I override addView()
method (similar to https://android.googlesource.com/platform/frameworks/support/+/81fdc55/design/src/android/support/design/widget/TextInputLayout.java#140 ), that is called during XML inflation:为此,我重写
addView()
方法(类似于https://android.googlesource.com/platform/frameworks/support/+/81fdc55/design/src/android/support/design/widget/TextInputLayout.java#140 ) ,即在 XML 膨胀期间调用:
class MyCustomWrapper @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
private val binding = MyCustomWrapper Binding.inflate(LayoutInflater.from(context), this, true)
override fun addView(child: View?) {
if (child is MyCustomView) {
// custom logic
} else {
super.addView(child)
}
}
}
Unfortunately, it doesn't work: the condition child is MyCustomView
is always false, in debugger child is only typed as LinearLayout
.不幸的是,它不起作用:条件
child is MyCustomView
始终为 false,在调试器中 child 仅键入为LinearLayout
。 Any ideas, how to fix this?任何想法如何解决这一问题?
you have to override你必须覆盖
override fun addView(child: View?, params: ViewGroup.LayoutParams?) {
...
}
addView(child: View?)
is invoked only for your MyCustomWrapperBinding
addView(child: View?)
仅为您的MyCustomWrapperBinding
调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.