Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getColor Error in API Level 23

Tags:

android

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.

like image 535
King Of The Jungle Avatar asked Aug 21 '15 10:08

King Of The Jungle


3 Answers

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.

like image 189
alanv Avatar answered Nov 02 '22 23:11

alanv


Try this..

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

instead

int color = getResources().getColor(R.color.color_name);
like image 9
uday Avatar answered Nov 03 '22 00:11

uday


As mentioned here, you can use ContextCompat as follows:

ContextCompat.getColor(context, R.color.color_name);
like image 8
MohanadMohie Avatar answered Nov 03 '22 01:11

MohanadMohie