Search code examples
androidkotlinandroid-drawable

How to return a Drawable asset as Integer?


In my app I am using this function to return a Drawable witch changed color:

fun setDrawableColor(icon: Drawable, color: Int): Drawable {
    val drawable = DrawableCompat.wrap(icon)
    DrawableCompat.setTint(drawable, getColor(color))
    return drawable
}

This works perfectly. However, I can't use it for example for setIcon() of a AlertDialog since it takes a Drawable as Integer like this setIcon(R.dawable.my_icon).

I need a similar function like above one, which does exactly the same thing but returns Drawable as Integer instead. How can I achieve that?


Solution

  • You can try this way but you need to pass the drawable name as parameter here

    fun getDrawableColorAsInt(icon: Drawable, color: Int, drawableName: String): Int {
            val drawable = DrawableCompat.wrap(icon)
            DrawableCompat.setTint(drawable, context!!.getColor(color))
            val resourceID = resources.getIdentifier(drawableName, "drawable", context!!.packageName)
            return resourceID
        }