从 XML 膨胀时,自定义 Android 视图的类型错误

问题描述

我有一个自定义视图,它扩展了 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>

为此,我重写了 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),true)
    
    override fun addView(child: View?) {
        if (child is MyCustomView) {
            // custom logic
        } else {
            super.addView(child)
        }
    }
}

不幸的是,它不起作用:条件 child is MyCustomView 始终为假,在调试器中子项仅输入为 LinearLayout。任何想法,如何解决这个问题?

解决方法

你必须覆盖

1,2,3,4,5 * * * * test.py >> /docs/cron.log

crontab: installing new crontab 仅为您的 override fun addView(child: View?,params: ViewGroup.LayoutParams?) { ... }

调用