Getcolor(Int Id) Deprecated on Android 6.0 Marshmallow (API 23)

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.

getResources().getColor() is deprecated

It looks like the best approach is to use:

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

eg:

yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
R.color.colorAccent))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

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

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>

Famous and old method getColor (int id) is deprecated. Api 23

Then finally i want to ask how to use (R.color.colorPrimary) without
any deprecation?

using ContextCompat.getColor(). E.g.

textView.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));

From the doc

Returns a color associated with a particular resource ID Starting in
M, the returned color will be styled for the specified Context's
theme.

getResources().getColor() showing deprecated even after API check

Use this ContextCompat.getColor(context,R.color.your_color);

getColor(int) is deprecated how i can use getColor(int,theme theme)

Use something as

    ResourcesCompat.getColor(getResources(), R.color.red, null)

(Prior to API level 23 the theme will not be applied, so it may be null.)

getColor Error in API Level 23

The old method is deprecated starting in API 23, and the new method only exists in API 23+. You are attempting to call the new method on a device running API <23.

You can either perform an API level check and call the appropriate method, or you can use ContextCompat.getColor(Context, int) from the support-v4 library.



Related Topics



Leave a reply



Submit