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!
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
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; }
No Comment to " Android getDrawable() deprecated API 22 Alternative "