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);

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());


Solution 4

Long since overdue, but my favorite is to use the Context:


where placeholder_image is the id of the resource. In your case, R.drawable.myresource.

Context can be an activity or the application. Pretty much wherever you are has reference to the context, which you can use to get the application's context.

Solution 5

In case anyone else comes across the problem I had, I was loading the image name from JSON and then needed to get the identifier. The second parameter of getIdentifier can be set to "drawable". This is a slight variation on @alia-ramli-ramli answer...

String uri = details.getString("circle").toLowerCase();

int imageResource = context.getResources().getIdentifier(uri, "drawable", context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);

Solution 6

You can check here

int resID = mContext.getResources().getIdentifier(stringfilename, "drawable", mContext.getPackageName());

you can also retrieve image from mipmap by replacing "drawable" with "mipmap" parameter of getIdentifier() method.

Solution 7

I had the same problem with ... the deprecated etc. etc. I solved in such a way with minimum API 14 okay.

ImageView imgPoster = viewCache.getImgPoster(resource);
String uri = "drawable/" + film.getPoster();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = ContextCompat.getDrawable(context, imageResource);

return convertView;