Using setImageDrawable dynamically to set image in an ImageView

前端 未结 17 1721
借酒劲吻你
借酒劲吻你 2020-12-04 08:22

I am generating a string from database dynamically which has the same name of image in drawable folder.

Now I want to set that value for ImageView

相关标签:
17条回答
  • 2020-12-04 09:02

    btnImg.SetImageDrawable(GetDrawable(Resource.Drawable.button_round_green));

    API 23 Android 6.0

    0 讨论(0)
  • 2020-12-04 09:08

    The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources class to resolve the string into that integer.

    Resources res = getResources();
    int resourceId = res.getIdentifier(
       generatedString, "drawable", getPackageName() );
    imageView.setImageResource( resourceId );
    

    This resolves your generated string into the integer that the ImageView can use to load the right image.

    Alternately, you can use the id to load the Drawable manually and then set the image using that drawable instead of the resource ID.

    Drawable drawable = res.getDrawable( resourceId );
    imageView.setImageDrawable( drawable );
    
    0 讨论(0)
  • 2020-12-04 09:09

    imageView.setImageDrawable(getResources().getDrawable(R.drawable.my_drawable));

    0 讨论(0)
  • 2020-12-04 09:10

    From API 22 use:

    Drawable myDrawable =  ResourcesCompat.getDrawable(getResources(), 
                            R.drawable.dos_red, null);
    
    0 讨论(0)
  • 2020-12-04 09:11

    I personally prefer to use the method setImageResource() like this.

    ImageView myImageView = (ImageView)findViewById(R.id.myImage);
    myImageView.setImageResource(R.drawable.icon);
    
    0 讨论(0)
提交回复
热议问题