Adam Varhegyi
Adam Varhegyi

Reputation: 9894

Reference to R.drawabe dynamically?

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?

Upvotes: 0

Views: 309

Answers (2)

Jordi
Jordi

Reputation: 616

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

Upvotes: 0

Alex Lockwood
Alex Lockwood

Reputation: 83313

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

Upvotes: 1

Related Questions