Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get drawable resource by string?

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)
like image 606
Polaris Nation Avatar asked Feb 20 '26 22:02

Polaris Nation


1 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 = "..."
)
like image 66
Philip Dukhov Avatar answered Feb 22 '26 10:02

Philip Dukhov