【问题标题】:Custom Android view has wrong type when inflating from XML从 XML 膨胀时,自定义 Android 视图的类型错误
【发布时间】: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


    【解决方案1】:

    你必须重写

    override fun addView(child: View?, params: ViewGroup.LayoutParams?) {
        ...
    }
    

    addView(child: View?) 仅为您的MyCustomWrapperBinding 调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      相关资源
      最近更新 更多