ResourcesCompat.getDrawable() vs AppCompatResources.getDrawable()

azizbekian picture azizbekian · Mar 24, 2017 · Viewed 15.7k times · Source

I'm a bit confused with these two APIs.

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

Return a drawable object associated with a particular resource ID and styled for the specified theme. Various types of objects will be returned depending on the underlying resource -- for example, a solid color, PNG image, scalable image, etc.

Prior to API level 21, the theme will not be applied and this method simply calls through to getDrawable(int).

AppCompatResources.getDrawable(Context context, int resId)

Return a drawable object associated with a particular resource ID.

This method supports inflation of vector and animated-vector resources on devices where platform support is not available.

Question

  1. What is the significant difference between these two classes (besides vector inflation)?
  2. Which one should I prefer to another and why?

Answer

Phan Van Linh picture Phan Van Linh · Jan 13, 2018

Here is my understand after some test

ContextCompat.getDrawable(@NonNull Context context, @DrawableRes int resId)

ResourcesCompat.getDrawable(@NonNull Resources res, @DrawableRes int id, @Nullable Theme theme)

AppCompatResources.getDrawable(@NonNull Context context, @DrawableRes int resId)

VectorDrawableCompat.create(@NonNull Resources res, @DrawableRes int resId, @Nullable Theme theme

The first thing see is VectorDrawableCompat and ResourcesCompat can specific theme

I) Without using

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); in onCreated of Application class

1) For vector image

  • API >= 21

    • ContextCompat work well
    • ResourcesCompat work well
    • AppCompatResources work well
    • VectorDrawableCompat work well
  • API < 21

    • ContextCompat crash
    • ResourcesCompat crash
    • AppCompatResources work well
    • VectorDrawableCompat work well

2) For normal image

  • In all level
    • ContextCompat work well
    • ResourcesCompat work well
    • AppCompatResources work well
    • VectorDrawableCompat crash

II) Using

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); in onCreated of Application class

1) For vector image

  • In all level
    • ContextCompat work well
    • ResourcesCompat work well
    • AppCompatResources work well
    • VectorDrawableCompat work well

2) For normal image

  • In all level
    • ContextCompat work well
    • ResourcesCompat work well
    • AppCompatResources work well
    • VectorDrawableCompat crash