Search code examples
kotlinattributesandroid-custom-viewandroid-drawable

Why does CustomView ignore drawables that are defined in app:srcCompat attribute?


When a custom view is created by subclassing an ImageView, will the custom view still be able to render drawable resources, as defined through the app:srcCompat="@drawable/some_drawing" attribute? I don't see a reason why it wouldn't, yet it doesn't work for me. Building and execution are clean, but the drawing doesn't appear. Is there a name space problem maybe?

res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="104dp"
        tools:layout_editor_absoluteY="251dp">

        <com.example.testapp.CustomView
            android:id="@+id/customView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/some_drawing" />

java/com.example.testapp/CustomView:

class CustomView : ImageView {
    constructor(context: Context) :
            super(context) {
    }

    constructor(context: Context, attributeSet: AttributeSet) :
            super(context, attributeSet) {
    }

    constructor(context: Context, attributeSet: AttributeSet, defStyle: Int) :
            super(context, attributeSet, defStyle) {
    }
}

Solution

  • You need to extend AppCompatImageView not ImageView