android - How to create Drawable from resource

ID : 10093

viewed : 30

Tags : androiddrawableandroid

Top 5 Answer for android - How to create Drawable from resource

vote vote

100

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); 
vote vote

87

This code is deprecated:

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

Use this instead:

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

71

The getDrawable (int id) method is deprecated 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); } 
vote vote

69

I would just like to add that if you are getting "deprecated" message when using getDrawable(...) you should use the following method from the support library instead.

ContextCompat.getDrawable(getContext(),R.drawable.[name]) 

You do not have to use getResources() when using this method.

This is equivalent to doing something like

Drawable mDrawable; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){     mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]); } else {     mDrawable = getResources().getDrawable(R.id.[name]); } 

This works on both pre and post Lollipop versions.

vote vote

59

Get Drawable from vector resource irrespective of, whether its vector or not:

AppCompatResources.getDrawable(context, R.drawable.icon); 

Note:
ContextCompat.getDrawable(context, R.drawable.icon); will produce android.content.res.Resources$NotFoundException for vector resource.

Top 3 video Explaining android - How to create Drawable from resource

Related QUESTION?