I\'m a bit confused with these two APIs.
ResourcesCompat.getDrawable(Resources res, int id, Resources.Theme theme)
Return a drawable
ResourcesCompat
, ContextCompat
and pretty much any class from support-v4 ending with Compat
saves you from writing if (Build.VERSION.SDK_INT >= X)
checks everywhere. That's it. For example instead of
final Drawable d;
if (Build.VERSION.SDK_INT < 21) {
// Old method, drawables cannot contain theme references.
d = context.getResources().getDrawable(R.drawable.some_image);
} else {
// Drawables on API 21 can contain theme attribute references.
// Context#getDrawable only exists since API 21.
d = context.getDrawable(R.drawable.some_image);
}
you can write
final Drawable d = ContextCompat.getDrawable(context, R.drawable.some_image);
The limits described in comments apply, for example
// This line is effectively equivalent to the above.
ResourcesCompat.getDrawable(context.getResources(), R.drawable.some_image, context.getTheme());
does not actually apply the theme attributes before Lollipop (this is said in the documentation). But you don't have to write if checks and your code does not crash on old devices because you're not actually using new APIs there.
AppCompatResources
on the other hand will actually help you bring new features to old platforms (support vectors, theme references in color state lists).
Which one should I prefer to another and why?
Use AppCompatResources
to get consistent results with the rest of appcompat-v7 library. You'll get:
getColorStateList
which can resolve colors with theme attribute references (such as android:alpha="?android:disabledAlpha"
),getDrawable
which supports inflating vectors on all platforms and these vector drawables also understand theme attribute references (e.g. android:tint="?colorControlNormal"
),ContextCompat
anyway.