android – Display an image from its name (Kotlin)

android – Display an image from its name (Kotlin)

You can get the resource using getIdentifier. Use the below snippet to get drawable from a resource by name

  1. pic1 is your drawable image name
  2. drawable is the resource folder
  3. android.demo is your package name (or your can use activity.getPackageName() to get package dynamically)

Kotlin

val identifier = resources.getIdentifier(pic1, drawable, android.demo)
imageView1.setImageResource(identifier)

Java

int identifier = getResources().getIdentifier(pic1, drawable,android.demo);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(identifier);

Or you can use reflections to get resource

try {
    Class res = R.drawable.class;
    Field field = res.getField(pic1);
    int drawableId = field.getInt(null);
    image.setImageResource(identifier);
}
catch (Exception e) {
    Log.e(MyTag, Failure to get drawable id., e);
}

android – Display an image from its name (Kotlin)

Leave a Reply

Your email address will not be published.