Android – How to create Drawable from resource

androiddrawable

I have an image res/drawable/test.png (R.drawable.test).
I want to pass this image to a function which accepts Drawable, e.g. mButton.setCompoundDrawables().

So how can I convert an image resource to a Drawable?

Best Answer

Your Activity should have the method getResources. Do:

Drawable myIcon = getResources().getDrawable( R.drawable.icon );


As of API version 21 this method is deprecated and can be replaced with:

Drawable myIcon = AppCompatResources.getDrawable(context, R.drawable.icon);

If you need to specify a custom theme, the following will apply it, but only if API is version 21 or greater:

Drawable myIcon =  ResourcesCompat.getDrawable(getResources(), R.drawable.icon, theme);