在Android中动态加载图像到ImageView中

6
我有一个包含100多个国家旗帜图片的数据库,存储在我的drawable文件夹中。
现在我想在ImageView中显示当前所在国家的国旗。
我使用 String country_variable = address.getCountryCode(); 获取当前所在国家。
然后我使用 flag.setImageDrawable(getResources().getDrawable(R.drawable.country_variable)); 来设置图片。
众所周知,R.drawable.country_variable不起作用,因为编译器找不到名为country_variable的图片。
那么,最好的方法是什么?

为什么不使用每个可绘制对象的国家代码进行命名,并使用哈希映射表呢? - techi.services
我做了。这些标志的名称为“fr.png”,“de.png”,“uk.png”等。 - Galip
抱歉,我没有恰当地解释清楚。hashmap<country_variable, int> 中的 int 是 R.drawable.<countrycode>。 - techi.services
2个回答

12

你可以使用getResources().getIdentifier()通过资源名称获取其ID。代码大致如下:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("drawable/" + country_variable, "drawable", getPackageName()));

1
谢谢!它起作用了!不过必须添加 .toLowerCase();。getCountryCode() 返回两个大写字母,而Android不允许在drawable映射中使用大写文件名。 - Galip

6

试试这个:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));

1
谢谢!它起作用了!不过必须添加 .toLowerCase();。getCountryCode() 返回两个大写字母,而Android不允许在drawable映射中使用大写文件名。 - Galip

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