How to create Drawable from resource

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

So how to convert a image resource to an Drawable ?


Your Activity should have the method getResources. Do:

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

This code is deprecated.

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

Use this instad.

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

The getDrawable (int id) method is depreciated as of API 22.

Instead you should use the getDrawable (int id, Resources.Theme theme) for API 21+

Code would look something like this.

Drawable myDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    myDrawable = context.getResources().getDrawable(id, context.getTheme());
} else {
    myDrawable = context.getResources().getDrawable(id);
}
链接地址: http://www.djcxy.com/p/63778.html

上一篇: 在画布上平铺一个位图

下一篇: 如何从资源创建Drawable