Android ImageView setImageResource in code

房东的猫 提交于 2019-12-20 08:49:16

问题


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)

My code (countryCode is the current countryCode in uppercase letters):

    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


回答1:


One easy way to map that country name that you have to an int to be used in the setImageResource method is:

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.




回答2:


This is how to set an image into ImageView using the setImageResource() method:

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



回答3:


you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);



回答4:


you may try this:-

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));


来源:https://stackoverflow.com/questions/12646354/android-imageview-setimageresource-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!