Home > front end >  Not imported ContextCompat in my android studio
Not imported ContextCompat in my android studio

Time:10-26

My Contextcompat is imported but it still gives this error

image enter image description here

my build.gradle

plugins {
        id 'com.android.application'
        id 'org.jetbrains.kotlin.android'
    }

android {
    namespace 'com.nzd.library'
    compileSdk 32

    defaultConfig {
        applicationId "com.nzd.library"
        minSdk 23
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.6.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
}

These two entered

android.useAndroidX=true android.enableJetifier=true

I paste the image in the question kindly see it. I am looking forward for the solution, if someone will help, it will be appreciated.

CodePudding user response:

It imported ContextCompat fine. Notice there is no error on the import line.

You are not supposed to instantiate ContextCompat like that. It has a private constructor and only static methods so it is similar to a Kotlin object.

To use ContextCompat, you call the function directly on ContextCompat. For example, to use its getColor function, you would do:

val myColor = ContextCompat.getColor(this, R.id.my_color)

The first argument is the Context. When in an Activity class, you can pass this as the first argument. In a Fragment, you would pass requireContext() as the first argument.

  • Related