Dynamically load Image in ImageView in Android

12,981

Solution 1

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

Solution 2

Try this:

flag.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(country_variable, "drawable", getPackageName()));
Share:
12,981
Galip
Author by

Galip

Updated on June 21, 2022

Comments

  • Galip
    Galip about 2 years

    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?

  • Galip
    Galip over 13 years
    Tnx! It works! had to add .toLowerCase(); though. getCountryCode() returns two uppercase letters and Android doesn't allow uppercase filenames in the drawable map.
  • Galip
    Galip over 13 years
    Tnx! It works! had to add .toLowerCase(); though. getCountryCode() returns two uppercase letters and Android doesn't allow uppercase filenames in the drawable map.