Search code examples
androidandroid-drawable

Android - set an image using @android:drawable/AnImage programmatically


I know how to use @drawable but how do I set @android:drawable/ic_image in code?

in XML, it would be

android:icon="@drawable/my_image"

or

android:icon="@mipmap/my_image"

and for android:drawable, it would be:

android:icon="@android:drawable/ic_menu_delete"

but how to do the latest in code to set an image?

And which should I use?


Solution

  • This will help you out. Don't use getResource().getDrawable(). Its deprecated.

    Android getResources().getDrawable() deprecated API 22

    So basically:

     Drawable drawable = ContextCompat.getDrawable(this, R.drawable.your_drawable);
        img.setBackgroundDrawable(drawable);
    

    For android drawables you do:

    ContextCompat.getDrawable(this, android.R.drawable.your_drawable);
    

    For Mipmaps:

    ContextCompat.getDrawable(this, R.mipmap.your_drawable);