getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)
Starting from Android Support Library 23,
a new getColor() method has been added to ContextCompat
.
Its description from the official JavaDoc:
Returns a color associated with a particular resource ID
Starting in M, the returned color will be styled for the specified Context's theme.
So, just call:
ContextCompat.getColor(context, R.color.your_color);
You can check the ContextCompat.getColor()
source code on GitHub.
tl;dr:
ContextCompat.getColor(context, R.color.my_color)
Explanation:
You will need to use ContextCompat.getColor(), which is part of the Support V4 Library (it will work for all the previous APIs).
ContextCompat.getColor(context, R.color.my_color)
If you don't already use the Support Library, you will need to add the following line to the dependencies
array inside your app build.gradle
(note: it's optional if you already use the appcompat (V7) library):
compile 'com.android.support:support-v4:23.0.0' # or any version above
If you care about themes, the documentation specifies that:
Starting in M, the returned color will be styled for the specified Context's theme
I don't want to include the Support library just for getColor, so I'm using something like
public static int getColorWrapper(Context context, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return context.getColor(id); } else { //noinspection deprecation return context.getResources().getColor(id); }}
I guess the code should work just fine, and the deprecated getColor
cannot disappear from API < 23.
And this is what I'm using in Kotlin:
/** * Returns a color associated with a particular resource ID. * * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor]. */@Suppress("DEPRECATION")@ColorIntfun getColorHelper(context: Context, @ColorRes id: Int) = if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);