代码中的Android ImageView setImageResource
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12646354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android ImageView setImageResource in code
提问by arielschon12
I have an imageView that i want to display a little icon of the country that you are currently in. I can get the country code, but problem is i can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
我有一个 imageView,我想显示您当前所在国家/地区的小图标。我可以获得国家/地区代码,但问题是我无法动态更改 imageView 资源。我的图片文件都是小写的(例如:国家代码=美国,图片文件=我们)
My code (countryCode is the current countryCode in uppercase letters):
我的代码(countryCode 是当前的countryCode 大写字母):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can i do this? Thanks in advance :D
现在,这当然行不通,因为 setImageResource 需要一个 int,那么我该怎么做呢?提前致谢
回答by Luksprog
One easy way to map that country name that you have to an int
to be used in the setImageResource
method is:
映射您必须int
在该setImageResource
方法中使用的国家名称的一种简单方法是:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
但是您真的应该尝试为要支持的国家/地区使用不同的文件夹资源。
回答by Jorgesys
This is how to set an image into ImageView
using the setImageResource()method:
这是ImageView
使用setImageResource()方法设置图像的方法:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
回答by Shekhar
you use that code
你使用那个代码
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
回答by sanjay
you may try this:-
你可以试试这个:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));