Donovan Tan
Donovan Tan

Reputation: 326

Android: ContextCompat.getColor(context, R.color.my_color), cannot resolve "getColor"

I know there are several similar questions regarding this has been asked here, however none of the solutions worked for me.

I have just transferred my application from Ecilpse(juno) to Android Studio 1.5.1; and from API 19 to API 23(compileSdkVersion).

Currently I encountered this error whereby "getResources().getColor(R.color.my_color)" is depreciated and cannot be used.

After searching online, I tried to use "ContextCompat.getColor(context, R.color.my_color)" instead. The error lies at the "getColor" part as it says that it cannot be resolved:

enter image description here

The method "ContextCompat" however allow me to use "getDrawable", "getExternalCacheDirs", "getExternalFilesDirs" and "getObbDirs"; just except for "getColor"

I have also ensure that I have these 2 in my app build.gradle (under dependencies{}):

Below are my imports for this class (DetailsActivity): enter image description here

Additionally, I have also tried using "ResourcesCompat" other than "ContextCompat"; and it still did not work out for me.

I am still a beginner at Android Development, working on a school project. Can anyone kindly provide some suggestions as of what I am doing wrong and point me towards the right direction? Thanks a lot in advance!

Upvotes: 3

Views: 23496

Answers (3)

Shoeb Siddique
Shoeb Siddique

Reputation: 2825

You can use this method.

This is the ContextCompat Developer Link from the Support Library:

public static final int getColor(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompat.getColor(context, id);
    } else { 
        return context.getResources().getColor(id);
    } 
} 

Upvotes: 4

and_dev
and_dev

Reputation: 3861

You don't have to use ContextCompat there if you are compiling with an API level greater than 24 as this is only a compatibility feature for early versions. You can also still use Context.getColor() But notice the method signature! If you just want a color in the default theme you only have to provide the int value of its reference: http://developer.android.com/reference/android/content/Context.html#getColor(int)

You are currently trying to access getColor() with two parameters (Color and Theme) which cannot work there as there is no method who supports these parameters. If you remove the 2nd parameter your current solution will work. But it would be more convenient to use Context or Resources directly and drop the v4 Appcompat reference if you don't need it.

Upvotes: 3

singh.indolia
singh.indolia

Reputation: 1291

Before to use this method, fist of all add the Dependencies in build.gradle script. Which is as follows:

dependencies {
    // other stuff here
    compile 'com.android.support:support-v4:23.0.0'
}

Upvotes: 1

Related Questions