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

Gal*_*lip 5 android image dynamic

我的可绘制文件夹中有100多张图像(国家标志)的数据库.

现在,我想在ImageView中显示您当前所在国家/地区的标志.

我和国家在一起 String country_variable = address.getCountryCode();

我用图像设置了图像 flag.setImageDrawable(getResources().getDrawable(R.drawable.country_variable));

众所周知,R.drawable.country_variable不起作用,因为编译器无法在drawable文件夹中找到名为country_variable的图像.

做这个的最好方式是什么?

rou*_*ill 12

您应该能够使用getResources().getIdentifier()来获取资源名称的id.就像是:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("drawable/" + country_variable, "drawable", getPackageName()));
Run Code Online (Sandbox Code Playgroud)


xil*_*il3 6

试试这个:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));
Run Code Online (Sandbox Code Playgroud)