-1

I recently ran into an exception when trying to create a custom class that extends AndroidX's AppCompatImageView.

android.view.InflateException: Binary XML file line #9 in {package}:layout/all_message_row: Binary XML file line // #9 in {package}:layout/all_message_row: Error inflating class {package}.ui.view.DotImageView

I use View Binding in this project and it happens whenever you inflate your View, like:

AllMessageRowBinding.inflate(layoutInflater, parent, false)

Here's the class declaration:

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

1 Answers1

0

I found out you need to add @JvmOverloads constructor like this:

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
}

Since View (and others that extend from it like ImageView) has multiple constructors, that informs the Kotlin compiler to automatically generate those constructors. Otherwise, at runtime, it can't find one of the constructors it expects while trying to inflate your View and an exception is thrown.

wildcat12
  • 975
  • 6
  • 13