Android getDrawable() deprecated API 22 Alternative

By James Thursday, August 11, 2016
There are several options to handle getDrawable() deprecation (the right and future proof way), depending on which kind of drawable is being loaded:
A) Drawables without theme attributes
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
For unstyled drawable the old way. This is probably what is needed.
Please note:  ResourcesCompat.getDrawable()  is not deprecated!
B) Drawables with theme attributes
ContextCompat.getDrawable(getActivity(), R.drawable.name);
For a styled Drawable as the Activity theme instructs.
C) Drawables with theme attributes from another theme
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
Explanation:
Android 21 (5.0 Lollipop) introduced some new theme attributes such as android:colorAccent that modify the appearance of drawables that hold references to those new theme attributes values.
The AppCompat library handles pre and post-Lollipop drawable styling for you.
If the deprecated getDrawable() method is used to obtain a drawable resource with theme attributes, A partially-styled drawable and a logcat warning will come as output. It can be seen in API 22 android.content.res.Resources source code:
@Deprecated
@Nullable
public Drawable getDrawable(int id) throws NotFoundException {
final Drawable d = getDrawable(id, null);
if (d != null && d.canApplyTheme()) {
Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
+ "attributes! Consider using Resources.getDrawable(int, Theme) or "
+ "Context.getDrawable(int).", new RuntimeException());
}
return d;
}

Post Tags:

James

I'm James. A full time Web Developer. I enjoy to make modern websites. I love technologies and write about these. Now I'm working with a softwere devloping firm. I would like to help people around the world acquiring knowledge through my writing.

No Comment to " Android getDrawable() deprecated API 22 Alternative "