ResourcesCompat.getDrawable() vs AppCompatResources.getDrawable()

后端 未结 4 1588
醉话见心
醉话见心 2021-01-30 08:45

I\'m a bit confused with these two APIs.

ResourcesCompat.getDrawable(Resources res, int id, Resources.Theme theme)

Return a drawable

4条回答
  •  旧时难觅i
    2021-01-30 09:35

    ContextCompat

    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

    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"),
    • appcompat-v7 drawables and colors like checkmarks or radio buttons will have proper colors defined by supplied context theme,
    • if the above does not apply it falls back to ContextCompat anyway.

提交回复
热议问题