Android - Open resource from @drawable String

I have:

String uri = "@drawable/myresource.png";

How can I load that in ImageView? this.setImageDrawable?


Solution 1:

If you really need to work with a string, try something like this:

private void showImage() {
    String uri = "drawable/icon";

    // int imageResource = R.drawable.icon;
    int imageResource = getResources().getIdentifier(uri, null, getPackageName());

    ImageView imageView = (ImageView) findViewById(R.id.myImageView);
    Drawable image = getResources().getDrawable(imageResource);
    imageView.setImageDrawable(image);
}

Else I would recommend you to work with R.* references like this:

int imageResource = R.drawable.icon;
Drawable image = getResources().getDrawable(imageResource);

Solution 2:

First, don't do that, as that @drawable syntax is meaningless in Java code. Use int resourceId=R.drawable.myresource.

If for some reason you do wind up a resource name and need the integer ID, use getIdentifier() on the Resources object.

Solution 3:

you can also add your own variable.. in my case scene.name between i followed @pfleidi answers. c stands for context.

String uri = "drawable/" + scene.name; 
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());

imageList.setImageResource(imageResource);