How can I get drawable resource by string?

Viewed 1101

I have their name as String which is in drawable folder. How can I access to drawable folder and pass drawable resource to change the Icon View.

val iconList = ["ic_apple","ic_banana","ic_melon"]

and ic_apple.png, ic_banana.png, ic_melon.png in my drawable folder.

Like, there was this with java's code.

String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
        
view.setBackground(drawable)
2 Answers

You can use LocalContext to get current context, and then use same methods as you used in view based Android:

val context = LocalContext.current
val drawableId = remember(name) {
    context.resources.getIdentifier(
        name,
        "drawable",
        context.packageName
    )
}
Image(
    painterResource(id = drawableId),
    contentDescription = "..."
)

I have tried the accepted answer there was a performance issue. If we use this solution with a list whenever there is a change in the string, the whole list will be recomputed so we need "derivedStateOf" side effect for this.

val drawableId by derivedStateOf {context.resources.getIdentifier(
                    name,
                    "drawable",
                    context.packageName
                ) }
Related