Home » Android » java – Cannot Resolve ContextCompat in Android

java – Cannot Resolve ContextCompat in Android

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have an AlertDialogue object called dialog. I am attempting to add an icon to it. I see that this syntax is now deprecated:

dialog.setIcon(getResources().getDrawable(R.drawable.myImage);

I’m reading everywhere that this should work:

dialog.setIcon(ContextCompat.getDrawable(context, R.drawable.myImage));

However, the ContextCompat syntax is not being recognized by Android Studio. Is there something that I should be importing? Thank you.

***Update: Thank’s to @Sharj for the correct answer below. I made a quick video too if you guys need a visual: https://www.youtube.com/watch?v=eFiaO0srQro&feature=youtu.be

How to&Answers:

ContextCompat is part of support library v4. Have you added support library 4 to your project?

android.support.v4.content.ContextCompat

You can include support library to your build.gradle file under app folder if you haven’t already

dependencies {
// other stuff here
    compile 'com.android.support:support-v4:23.0.0'
// update the 23.0.0 to latest version available

}

Answer:

androidx.core.content.ContextCompat

from AndroidX dependency

implementation 'androidx.appcompat:appcompat:1.1.0'

Answer:

I had the same issue and this and a few more posts helped me.
With Android studio you have multiple Gradle files.

I got my code to work by adding the dependencies section into Gradle (Module : Library) or the file that has “android {” …

dependencies {
        // other stuff here
        compile 'com.android.support:support-v4:23.+'
        // update the 23.0.0 to latest version available
    }

Answer:

If you are using Android gradle plugin 3.0.1, add google() to your allProjects repositories in the build.gradle file (project level) then sync

like this:

allprojects {
    repositories {
        google()
        ....
        //other repos
    }
}

Answer:

Adding this to build.gradle(Module:App) under dependencies resolved the problem

compile 'com.android.support:support-v4:23.0.0'