0

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)
Maradiya Krupa
  • 213
  • 1
  • 6
  • Show us the code that's not working for you. – Mike M. Mar 15 '22 at 13:52
  • @MikeM. I have edited my question and added the code snipped which I have tried. – Maradiya Krupa Mar 15 '22 at 14:28
  • Cool. You want to go with the `TypedArray` approach; the other one is for values you've set in the theme. The `TypedArray` one looks OK, at first glance, but you'd need to make sure that `attrs` isn't null there. If it is, there might be an issue elsewhere, like with the constructor setup. – Mike M. Mar 15 '22 at 14:33
  • 1
    I just noticed, though, that you're using `getResourceId()` there. Are you really trying to get the resource ID? Or do you just want the `Drawable` object? 'cause `TypedArray` has a `getDrawable()` that might be what you actually want there. – Mike M. Mar 15 '22 at 14:35
  • 1
    Thanks @MikeM. `getDrawable()` I was looking for. – Maradiya Krupa Mar 15 '22 at 14:47

1 Answers1

2

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!

Kostek
  • 283
  • 3
  • 10