28

I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)

My code (countryCode is the current countryCode in uppercase letters):

String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);

Now, of course this will not work because setImageResource wants an int, so how can I do this?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
rel-s
  • 6,108
  • 11
  • 38
  • 50

5 Answers5

38

One easy way to map that country name that you have to an int to be used in the setImageResource method is:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);

But you should really try to use different folders resources for the countries that you want to support.

user
  • 86,916
  • 18
  • 197
  • 190
35

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);
dimcookies
  • 1,930
  • 7
  • 31
  • 37
Shekhar
  • 151
  • 1
  • 2
  • 20
0

You can use this code:

// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];

// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...

// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
   if(countriesId[i][0].equals(countryCode))
      break;
}
// Now "i" is the index of the country

img.setImageResource(Integer.parseInt(countriesId[i][1]));
Avi
  • 362
  • 1
  • 3
  • 11
-2

you may try this:-

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));
sanjay
  • 2,116
  • 3
  • 19
  • 25
  • 2
    That didn't help, getDrawable() wants an int as well when i am providing the "R.Drawable.image_name" as a string variable.. Any way around that? – rel-s Sep 28 '12 at 19:51