Android 动态引用R.drawabe?
我的应用程序中有大约200多个国家的名字。 每个国家有200多个国旗图标。 国旗图标名称等于国家名称,如下所示: 国家名称:ENG,图标名称ENG.png 我想在我的应用程序中列出它们以选择国家。 我不想建立手动布局,并为每个文本视图添加200+图标 我的问题是,我能以某种方式动态添加吗 大概是这样的:Android 动态引用R.drawabe?,android,android-image,android-resources,Android,Android Image,Android Resources,我的应用程序中有大约200多个国家的名字。 每个国家有200多个国旗图标。 国旗图标名称等于国家名称,如下所示: 国家名称:ENG,图标名称ENG.png 我想在我的应用程序中列出它们以选择国家。 我不想建立手动布局,并为每个文本视图添加200+图标 我的问题是,我能以某种方式动态添加吗 大概是这样的: private void setIcon(String iconName) { countryIcon.setBackgroundResource(R.drawable. /* and
private void setIcon(String iconName)
{
countryIcon.setBackgroundResource(R.drawable. /* and i need the magic here*/ +iconName )
}
因此,我可以使用param动态引用R.drawable吗?尝试以下操作:
private void setIcon(String iconName) {
Resources res = getResources();
int imageResource = res.getIdentifier("drawable/" + iconName, null, getPackageName());
Drawable image = res.getDrawable(imageResource);
countryIcon.setBackgroundResource(image);
}
如果你有一个模式,这一点都不难。 这里有一个例子。我这样做是为了根据每个行对象的标志ID在ListView中加载标志图像。获得语言id后,我将获得与图标名称相同的语言密钥(字符串):
int ico_id, int visible=View.visible();
String flag;
Bitmap icona;
flag= (MyWharehouse.getLangKey(language_id.get(position))).toLowerCase(); //get the image.png name
ico_id = a.getResources().getIdentifier(flag, "drawable", a.getString(R.string.package_str));
icona = BitmapFactory.decodeResource(a.getResources(), ico_id);
((ImageView)a.findViewById(R.id.im_lang_01)).setImageBitmap(icona); //changing the image
特别是这可能会帮助您,请点击此链接