Dynamically upload image to ImageView in Android

I have this database with over 100 images (country flags) in my folder.

Now I want to display the flag of the country you are currently in in ImageView.

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

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

As you all know, R.drawable.country_variable does not work because the compiler cannot find the image named country_variable in the transfer folder.

What is the best way to do this?

+5
source share
2 answers

You can use getResources (). getIdentifier () to get the identifier by resource name. Sort of:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("drawable/" + country_variable, "drawable", getPackageName()));
+12
source

Try the following:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));
+6

All Articles