24

getResources().getColor(R.color.color_name) is now deprecated in API Level 23 but can work by adding a Color Theme as a second parameter like

getResources().getColor(R.color.color_name, Theme)
according to the new documentation but when I pass in null value for the Theme like

getResources().getColor(R.color.color_name, null)
my app crashes. Maybe I am missing something in my understanding. Please help, thanx in advance.

King Of The Jungle
  • 735
  • 1
  • 11
  • 17

4 Answers4

78

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.

alanv
  • 23,966
  • 4
  • 93
  • 80
10

Try this..

int color = Color.parseColor(getResources().getString(R.color.color_name));

instead

int color = getResources().getColor(R.color.color_name);
uday
  • 1,348
  • 12
  • 27
  • 2
    This method is great. It may not be optimal, but it's straightforward and works. Best of all, it gets me out of the science project getting color from a resource has become. – strangeluck Nov 06 '15 at 16:32
9

As mentioned here, you can use ContextCompat as follows:

ContextCompat.getColor(context, R.color.color_name);
Community
  • 1
  • 1
MohanadMohie
  • 1,033
  • 1
  • 10
  • 17
0

You can use this to set color from adapter class

View view=super.getView(position,convertView,parent);
view.setBackgroundColor(ContextCompat.getColor(context, R.color.blue_100));
Teshie Ethiopia
  • 586
  • 8
  • 27