Android ImageView setImageResource in code

后端 未结 5 465
太阳男子
太阳男子 2020-12-13 05:01

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

相关标签:
5条回答
  • 2020-12-13 05:37

    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.

    0 讨论(0)
  • 2020-12-13 05:37

    you use that code

    ImageView[] ivCard = new ImageView[1];
    
    @override    
    protected void onCreate(Bundle savedInstanceState)  
    
    ivCard[0]=(ImageView)findViewById(R.id.imageView1);
    
    0 讨论(0)
  • 2020-12-13 05:40

    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]));
    
    0 讨论(0)
  • 2020-12-13 05:56

    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);
    
    0 讨论(0)
  • 2020-12-13 05:56

    you may try this:-

    myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));
    
    0 讨论(0)
提交回复
热议问题