Android ImageView setImageResource in code

119,708

Solution 1

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.

Solution 2

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);
Share:
119,708

Related videos on Youtube

arielschon12
Author by

arielschon12

Updated on September 27, 2020

Comments

  • arielschon12
    arielschon12 over 3 years

    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?

  • arielschon12
    arielschon12 over 11 years
    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?