[android] getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

The Resources.getColor(int id) method has been deprecated.

@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
    return getColor(id, null);
}

What should I do?

The answer is


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")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
    if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);

Use the getColor(Resources, int, Theme) method of the ResourcesCompat from the Android Support Library.

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

I think it reflect better your question than the getColor(Context, int) of the ContextCompat since you ask about Resources. Prior to API level 23, the theme will not be applied and the method calls through to getColor(int) but you'll not have the deprecated warning. The theme also may be null.


The best equivalent is using ContextCompat.getColor and ResourcesCompat.getColor . I made some extension functions for quick migration:

@ColorInt
fun Context.getColorCompat(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)

@ColorInt
fun Fragment.getColorCompat(@ColorRes colorRes: Int) = activity!!.getColorCompat(colorRes)

@ColorInt
fun Resources.getColorCompat(@ColorRes colorRes: Int) = ResourcesCompat.getColor(this, colorRes, null)

I got frustrated too. My need was very straightforward. All I wanted was the ARGB color from the resources, so I wrote a simple static method.

protected static int getARGBColor(Context c, int resId)
        throws Resources.NotFoundException {

    TypedValue color = new TypedValue();
    try {
        c.getResources().getValue(resId, color, true);
    }
    catch (Resources.NotFoundException e) {
        throw(new Resources.NotFoundException(
                  String.format("Failed to find color for resourse id 0x%08x",
                                resId)));
    }
    if (color.type != TYPE_INT_COLOR_ARGB8) {
        throw(new Resources.NotFoundException(
                  String.format(
                      "Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
                      resId, color.type))
        );
    }
    return color.data;
}

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


in activity used ContextCompat

ContextCompat.getColor(context, R.color.color_name)

in Adaper

private Context context;


context.getResources().getColor()

If you don't necessarily need the resources, use parseColor(String):
Color.parseColor("#cc0066")


In Your RecyclerView in Kotlin

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

For all the Kotlin users out there:

context?.let {
    val color = ContextCompat.getColor(it, R.color.colorPrimary)
    // ...
}

In Android Marshmallow many methods are deprecated.

For example, to get color use

ContextCompat.getColor(context, R.color.color_name);

Also to get drawable use

ContextCompat.getDrawable(context, R.drawable.drawble_name);

If your current min. API level is 23, you can simply use getColor() like we are using to get string resources by getString():

//example
textView.setTextColor(getColor(R.color.green));
// if `Context` is not available, use with context.getColor()

You can constraint for API Levels below 23:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

but to keep it simple, you can do like below as accepted answer:

textView.setTextColor(ContextCompat.getColor(context, R.color.green))

From Resources.

From ContextCompat AndroidX.

From ContextCompat Support


In Kotlin, you can do:

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

if requireContext() is accessible from where you are calling the function. I was getting an error when trying

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-resources

Failed linking file resources Execution failed for task ':app:processDebugResources' even with latest build tools getResources().getColor() is deprecated getColor(int id) deprecated on Android 6.0 Marshmallow (API 23) Android getResources().getDrawable() deprecated API 22 Android Studio cannot resolve R in imported project? Android XXHDPI resources Android ImageView setImageResource in code format statement in a string resource file Lint: How to ignore "<key> is not translated in <language>" errors?

Examples related to android-6.0-marshmallow

Android 6.0 multiple permissions How to check the multiple permission at single request in Android M? Android marshmallow request permission? Get JSON Data from URL Using Android? Storage permission error in Marshmallow Android 6.0 Marshmallow. Cannot write to SD Card How to programmatically open the Permission Screen for a specific app on Android Marshmallow? Neither user 10102 nor current process has android.permission.READ_PHONE_STATE ConnectivityManager getNetworkInfo(int) deprecated getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

Examples related to android-mnc

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)