【发布时间】:2021-03-18 10:45:54
【问题描述】:
我有一个自定义视图,它扩展了 LinearLayout:
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {
private val binding = MyCustomViewBinding.inflate(LayoutInflater.from(context), this, true)
// ...
}
而且我需要定义一个自定义包装器(类似于TextInputLayout),它可以包含一个子MyCustomView 对象,并且有一个特殊的逻辑来膨胀它。所以我希望能够在 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>
为此,我重写了在 XML 膨胀期间调用的 addView() 方法(类似于 https://android.googlesource.com/platform/frameworks/support/+/81fdc55/design/src/android/support/design/widget/TextInputLayout.java#140 ):
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)
}
}
}
不幸的是,它不起作用:条件child is MyCustomView 始终为假,在调试器中子项仅键入为LinearLayout。任何想法,如何解决这个问题?
【问题讨论】:
标签: java android kotlin android-custom-view custom-view