在代码中设置Android ImageView的setImageResource

28

我有一个imageView,想在其中显示当前所在国家的小图标。我可以获取国家代码,但问题是我无法动态更改imageView的资源。我的图像文件全部为小写(例如:国家代码=US,则图像文件=us)。

我的代码(countryCode是当前大写字母的国家代码):

String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);

当然,这样做是行不通的,因为setImageResource需要一个int参数,那么我该怎么做呢?

5个回答

38

将你拥有的国家名称映射为可用于setImageResource方法的int的一种简单方法是:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);

但您应该尝试为您想要支持的国家使用不同的文件夹资源。


35

使用 setImageResource() 方法来将图片设置到 ImageView 中的步骤如下:

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

0

你使用那段代码

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

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

0
你可以使用这段代码:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];

// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...

// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
   if(countriesId[i][0].equals(countryCode))
      break;
}
// Now "i" is the index of the country

img.setImageResource(Integer.parseInt(countriesId[i][1]));

-2

你可以尝试这个:

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

2
那并没有帮助,当我将“R.Drawable.image_name”作为字符串变量提供时,getDrawable()也需要一个整数。有什么解决方法吗? - arielschon12

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