2

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)
Pylyp Dukhov
  • 38,521
  • 10
  • 57
  • 92
Polaris Nation
  • 831
  • 1
  • 14
  • 35
  • Your question isn't clear. What do you mean by "String which is in a drawable folder"? Strings are stored in the values resource and not drawables. And what do you mean by "Icon View"? Please update your post with more accurate information. – Johann Nov 22 '21 at 08:17
  • @Johann Update the post. Please check it out. – Polaris Nation Nov 22 '21 at 08:28
  • 1
    Is this what you are looking for: https://stackoverflow.com/a/4428288/753632 – Johann Nov 22 '21 at 08:46

1 Answers1

5

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 = "..."
)
Pylyp Dukhov
  • 38,521
  • 10
  • 57
  • 92