【问题标题】:InflateException when extending Android View扩展 Android 视图时出现 InflateException
【发布时间】:2020-06-03 18:26:53
【问题描述】:

我最近在尝试创建扩展 AndroidX 的 AppCompatImageView 的自定义类时遇到了异常。

android.view.InflateException:{package} 中的二进制 XML 文件第 9 行:layout/all_message_row:二进制 XML 文件行 // #9 in {package}:layout/all_message_row: Error inflating class {package}.ui.view.DotImageView

我在这个项目中使用了 View Binding,每当你给你的 View 充气时就会发生这种情况,比如:

AllMessageRowBinding.inflate(layoutInflater, parent, false)

这是类声明:

class DotImageView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: androidx.appcompat.widget.AppCompatImageView(context, attrs, defStyleAttr) {
    // rest of the class logic here
}

【问题讨论】:

    标签: android kotlin exception imageview inflate-exception


    【解决方案1】:

    我发现你需要像这样添加@JvmOverloads constructor

    class DotImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : androidx.appcompat.widget.AppCompatImageView(context, attrs, defStyleAttr) {
        // rest of the class logic here
    }
    

    由于 View(以及其他从它扩展而来的 ImageView)有多个构造函数, 通知 Kotlin 编译器自动生成这些构造函数。否则,在运行时,它无法找到它所期望的构造函数之一,同时尝试膨胀您的视图并引发异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多