简体   繁体   English

Android ImageView设置图像源

[英]Android ImageView setting source of image

I'm trying to set the source of my image, but I get an error. 我正在尝试设置图像的来源,但是我收到了错误。

String test1 = pref.getString("test", "ERROR");
String drawable1 = "R.drawable."+test1;
myImage.setImageResource(drawable1);

I've tried setting int drawable1 = "R.drawable."+test1; 我试过设置int drawable1 = "R.drawable."+test1; , but it still doesn't work. ,但它仍然无法正常工作。 I know it's a mismatch of types, but I can't seem to figure out a way to get it done. 我知道它是不匹配的类型,但我似乎无法找到一种方法来完成它。

It seems you could break the problem down even further and say how do you make this work? 看来你可以进一步解决这个问题,并说你如何使这项工作?

String drawable1 = "R.drawable.myImage";
myImage.setImageResource(drawable1);

Any ideas? 有任何想法吗?

I've tried setting int drawable1 = "R.drawable."+test1; 我试过设置int drawable1 = "R.drawable."+test1; , but it still doesn't work. ,但它仍然无法正常工作。

You need to use getIdentifier() to properly build resource ids from Strings: 您需要使用getIdentifier()从字符串中正确构建资源ID:

int drawable1 = getResources().getIdentifier(test1, "drawable", getPackageName());

(There are now two other answer that suggest this same thing... Did I miss something or did they just feel like repeating what's already been stated?) (现在还有另外两个答案表明同样的事情......我是否错过了某些内容,或者他们只是想重复已经说过的内容?)


As a note, if your Image is large or causes a noticable delay while loading the documentation on setImageResources() has alternate suggestions: 请注意,如果您的Image很大或在加载setImageResources()上的文档时导致明显的延迟,则有其他建议:

This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. 这会在UI线程上进行Bitmap读取和解码,这会导致延迟打嗝。 If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead. 如果这是一个问题,请考虑使用setImageDrawable(android.graphics.drawable.Drawable)setImageBitmap(android.graphics.Bitmap)BitmapFactory

Assuming you have a context (use this if the code is within an activity) 假设您有一个context (如果代码在一个活动中,请使用this context

int resId = context.getResources().getIdentifier(test1 , "drawable", cw.getPackageName());
myImage.setImageResource(resId);

Use 采用

 int drawable1 =  getResources().getIdentifier(test1, "drawable", getPackageName();

To learn more how to Get Resources by Name see this link 要了解更多如何按名称获取资源,请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM