我有:
String uri = "@drawable/myresource.png";
如何在 ImageView 中加载这个资源?使用 this.setImageDrawable 吗?
我有:
String uri = "@drawable/myresource.png";
如何在 ImageView 中加载这个资源?使用 this.setImageDrawable 吗?
如果你确实需要使用字符串,可以尝试类似这样的方法:
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);
}
否则,我建议您像这样使用R.*引用:
int imageResource = R.drawable.icon;
Drawable image = getResources().getDrawable(imageResource);
首先,不要这样做,因为在Java代码中@drawable
语法是无意义的。请使用int resourceId=R.drawable.myresource
。
如果你最终确实需要资源名称并且需要整数ID,请在Resources
对象上使用getIdentifier()
函数。
您也可以添加自己的变量...在我的情况下,我遵循了@pfleidi的答案,其中"c"代表上下文,"scene.name"则表示场景名称。
String uri = "drawable/" + scene.name;
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
imageList.setImageResource(imageResource);
虽然早就过时了,但我最喜欢使用上下文:
context.getApplicationContext().getResources().getDrawable(R.drawable.placeholder_image)
其中placeholder_image是资源的id名称。在你的情况下,使用R.drawable.myresource
。
上下文(context)可以是一个活动(activity)或应用程序(application)。无论你在哪里,都可以引用上下文(context),你可以使用它来获取应用程序的上下文(context)。
int resID = mContext.getResources().getIdentifier(stringfilename, "drawable", mContext.getPackageName());
iv_imageview.setImageDrawable(ContextCompat.getDrawable(mContext,resID));
您还可以通过将getIdentifier()方法中的参数“drawable”替换为“mipmap”,从mipmap中检索图像。
如果其他人遇到了我遇到的问题,我是从JSON中加载图像名称,然后需要获取标识符。getIdentifier的第二个参数可以设置为“drawable”。这是对@alia-ramli-ramli答案的略微变化...
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);
我曾经遇到过相同的问题,与...废弃等等有关。我通过最低API 14的方式解决了这个问题。
...
...
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;
...
...