Search code examples
androidandroid-theme

Why is getResources().getColor(int) deprecated?


The document says:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

And many posts point to the ContextCompat.getColor(Context, int) method as a replacement.

Also the document explains the Theme parameter:

theme Resources.Theme: The theme used to style the color attributes, may be null.

Can you explain how can the theme affects the color?


Solution

  • Some complex colors like android.content.res.GradientColor (which are used inside a VectorDrawable) need a Theme in order to inflate the gradient, since you could have a definition like:

    <gradient xmlns:android="http://schemas.android.com/apk/res/android">
       <android:startColor="?android:attr/colorPrimary"/>
       <android:endColor="?android:attr/colorControlActivated"/>
       <android:type="linear"/>
     </gradient>