Home » Android » How do you obtain a Drawable object from a resource id in android package?

How do you obtain a Drawable object from a resource id in android package?

Posted by: admin March 10, 2020 Leave a comment


I need to get a Drawable object to display on an image button. Is there a way to use the code below (or something like it) to get an object from the android.R.drawable.* package?

for example if drawableId was android.R.drawable.ic_delete

How to&Answers:
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);


As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

You should use the following code from the support library instead:

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

Using this method is equivalent to calling:

    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);


As of API 21, you could also use:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)


best way is


OR this for Drawable left and something like that for right etc.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);


getResources().getDrawable() is now deprecated


From API 21 getDrawable(int id) is deprecated. So now you need to use

ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)

But Best way to do is : You should create one common class for get drawable and colors because if any thing change or deprecate in future then you no need to change everywhere in your project.You just change in this method

object ResourceUtils {
    fun getColor(context: Context, color: Int): Int {
        return ResourcesCompat.getColor(context.getResources(), color, null)

    fun getDrawable(context: Context, drawable: Int): Drawable? {
        return ResourcesCompat.getDrawable(context.getResources(), drawable, null)

use this method like :

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)