0

I got about 200+ Country names in my app. I got 200+ flag icons for each country. The flag icons names are equals the country names, so like:

Country name: ENG, icon name eng.png

I want to make a list of them in my app to select country. I dont want to build the layout by manually and add 200+ icons for each and every TextView...

My question is, can i add dynamically somehow ?

Something like this:

private void setIcon(String iconName)
{
     countryIcon.setBackgroundResource(R.drawable. /* and i need the magic here*/ +iconName )
}

So can i reference to R.drawable dynamically by somehow with param?

Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222
  • [Have look at this post](http://stackoverflow.com/a/8038334/593709) and specially [this one](http://stackoverflow.com/a/6679476/593709) – Adil Soomro May 04 '12 at 07:11
  • This may help you, http://stackoverflow.com/questions/7941304/android-reference-things-in-r-drawable-using-variables – Ponmalar May 04 '12 at 07:15
  • Follow this Link http://w2davids.wordpress.com/android-listview-with-iconsimages-and-sharks-with-lasers/ – Krishnakant Dalal May 04 '12 at 07:17

2 Answers2

1

Try this:

private void setIcon(String iconName) {
    Resources res = getResources();
    int imageResource = res.getIdentifier("drawable/" + iconName, null, getPackageName());

    Drawable image = res.getDrawable(imageResource);
    countryIcon.setBackgroundResource(image);
}
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
0

If you've a pattern, is not difficult at all. Here's an example. I did this for loading flag-images in a ListView depending the flag IDs of each row-object. Once i've the language_id i get the language_KEY (String) which is the same as my icon's name:

   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
Jordi
  • 616
  • 2
  • 9
  • 16