getResources().getColor() is deprecated

David picture David · Aug 5, 2015 · Viewed 203.9k times · Source

Using: buildToolsVersion "22.0.1" , targetSdkVersion 22 in my gradle file.

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

What should I use instead?

Answer

Barry Irvine picture Barry Irvine · Aug 25, 2015

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.