Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load Image in ImageView in Android

I have this database of 100+ images (of country flags) in my drawable folder.

Now I want to display the flag of the country you're currently in, in an ImageView.

I get the country with String country_variable = address.getCountryCode();

And I set the image with flag.setImageDrawable(getResources().getDrawable(R.drawable.country_variable));

As you all know R.drawable.country_variable wont't work because the compiler can't find a image named country_variable in the drawable folder.

What is the best way to do this?

like image 505
Galip Avatar asked Nov 23 '10 13:11

Galip


2 Answers

You should be able to use getResources().getIdentifier() to get the id by the resource name. Something like:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("drawable/" + country_variable, "drawable", getPackageName()));
like image 196
roundhill Avatar answered Sep 23 '22 17:09

roundhill


Try this:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));
like image 27
xil3 Avatar answered Sep 23 '22 17:09

xil3