Get attrs value in customview kotlin class when format="reference"

643 Views Asked by At

I have created one CustomView class where I want to get drawable dynamically. So for that have created attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="myImage" format="reference"/>
    </declare-styleable>
</resources>

And then set this attrs through xml file like below:

<com.example.myapplication.CustomView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:myImage="@drawable/my_icon"/>

Now I want to get this myImage value in my CustomView class how can i get it?

I have already tried many ways to get it by TypedValue and TypedArray but not able to get it.

val typedValue = TypedValue()
        context.theme.resolveAttribute(R.attr.myImage, typedValue, true)
        val imageResId = ContextCompat.getDrawable(context,typedValue.resourceId)


val typedArray =
            context.theme.obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0)
        val imageResId = typedArray.getResourceId(R.styleable.CustomView_myImage,0)
1

There are 1 best solutions below

0
Kostek On

You are almost there, this is a working code:

val typedArray = context.obtainStyledAttributes(it, R.styleable.CustomView, 0, 0)
val image = typedArray.getResourceId(R.styleable.CustomView_ myImage, -1) // the -1 parameter could be your placeholder e.g. R.drawable.placeholder_image

and then you have the resource of your drawable that you can work with, as for the example:

imageView.setImageDrawable(ContextCompat.getDrawable(context, image))

or if you would like to get a drawable directly call:

val image = typedArray.getDrawable(R.styleable.CustomView_myImage)

but remember that this way your drawable might be null.

Enjoy coding!