Android - Open resource from @drawable String

2019-01-02 20:27发布

I have:

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

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

标签: android
7条回答
闭嘴吧你
2楼-- · 2019-01-02 21:05

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);
viewHolder.unit_circle.setImageDrawable(image);
查看更多
人气声优
3楼-- · 2019-01-02 21:09

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.

查看更多
唯独是你
4楼-- · 2019-01-02 21:09

You can check here

int resID = mContext.getResources().getIdentifier(stringfilename, "drawable", mContext.getPackageName());
iv_imageview.setImageDrawable(ContextCompat.getDrawable(mContext,resID)); 

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

查看更多
谁念西风独自凉
5楼-- · 2019-01-02 21:11

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);
查看更多
余生请多指教
6楼-- · 2019-01-02 21:15

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);
imgPoster.setImageDrawable(image);

return convertView;
...
...

查看更多
怪性笑人.
7楼-- · 2019-01-02 21:20

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

context.getApplicationContext().getResources().getDrawable(R.drawable.placeholder_image)

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.

查看更多
登录 后发表回答