安卓 - 从@drawable的字符串中打开资源

63

我有:

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

如何在 ImageView 中加载这个资源?使用 this.setImageDrawable 吗?

7个回答

172

如果你确实需要使用字符串,可以尝试类似这样的方法:

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

2
我正在从一些JSON中加载图像名称,URI开头没有包含“drawable /”,因此我无法获取资源。在这种情况下,您可以将第二个参数设置为“getIdentifier()”的“drawable”。 - Flexicoder
请注意,如果您使用它,Android Studio 将视其为未使用的资源,因此“重构/删除未使用的资源”选项将无法处理它。 - gturedi
1
请记住,您不应该将图像扩展名添加到URI中,并且必须在URI的开头添加“drawable/”。 - Mahdi Astanei

25

首先,不要这样做,因为在Java代码中@drawable语法是无意义的。请使用int resourceId=R.drawable.myresource

如果你最终确实需要资源名称并且需要整数ID,请在Resources对象上使用getIdentifier()函数。


4
谢谢,你给我方法的名称后,我很容易就找到了这个页面 -> http://www.anddev.org/viewtopic.php?p=35661 - nikib3ro
@kape123 感谢您的评论。这对我在使其工作方面很有帮助。 - nikhil

11

您也可以添加自己的变量...在我的情况下,我遵循了@pfleidi的答案,其中"c"代表上下文,"scene.name"则表示场景名称。

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

imageList.setImageResource(imageResource);

6

虽然早就过时了,但我最喜欢使用上下文:

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

其中placeholder_image是资源的id名称。在你的情况下,使用R.drawable.myresource

上下文(context)可以是一个活动(activity)或应用程序(application)。无论你在哪里,都可以引用上下文(context),你可以使用它来获取应用程序的上下文(context)。


pfleidi的回答正在访问相同的方法-活动是上下文,因此当他调用getResources()时,他使用当前活动作为上下文来到达您所在的位置。编辑:不完全相同,您正在访问全局应用程序上下文,而不是直接使用活动(或服务)上下文。 - MaximumGoat

4
您可以在此处查看相关信息:Resource.getIdentifier()
int resID = mContext.getResources().getIdentifier(stringfilename, "drawable", mContext.getPackageName());
iv_imageview.setImageDrawable(ContextCompat.getDrawable(mContext,resID)); 

您还可以通过将getIdentifier()方法中的参数“drawable”替换为“mipmap”,从mipmap中检索图像。


4

如果其他人遇到了我遇到的问题,我是从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);

0

我曾经遇到过相同的问题,与...废弃等等有关。我通过最低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;
...
...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接