5

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)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Polaris Nation
  • 1,085
  • 2
  • 18
  • 49
  • 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

2 Answers2

13

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 = "..."
)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Use of getIdentifier is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code – Darksymphony Feb 01 '23 at 10:15
  • 1
    @Darksymphony this is a reasonable warning, which says that you should use `R.drawable.ic_your_name` whenever it's possible - by doing this you'll get a build time warning when your resource is removed instead of a crash(or empty resource, not sure what'll happen on a wrong string). But this question is especially about getting resource by string - and yes, it's not safe in the first place, so you should only use it when you know what're you doing. A usage possible scenario is sending image name from the server. – Phil Dukhov Feb 01 '23 at 11:44
0

it will also work with the ressourceString

val context = LocalContext.current
val text = stringResource(id = 
LocalContext.current.resources.getIdentifier(
    "Error_verification_code",
    "string",
    context.packageName
))
JustSightseeing
  • 1,460
  • 3
  • 17
  • 37