如何修复错误:Could not find method implementation() for arguments on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

2021年11月29日19:48:57 发表评论 4,493 次浏览

了解如何在无法识别implementation时解决 Gradle 异常。

如何修复错误:Could not find method implementation() for arguments on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

implementation指令是用于库声明的依赖配置。它是在 Gradle 3 中引入的。因此,当 Gradle 无法识别implementation指令时,总是会触发此异常。

如何修复错误Could not find method implementation?在本文中,我将向你解释在 Android Studio 中解决此问题的可能方法。

可能的解决方案 #1(错误的 build.gradle)

Could not find method implementation解决办法:你很可能正在尝试在项目build.gradle文件中添加依赖项。你可能知道,你不应该在 Project gradle 中包含依赖项,因为你应该在单个模块上添加依赖项build.gradle

如何修复错误:Could not find method implementation() for arguments on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

因此,如果你像这样在项目 gradle 中添加依赖项:

// Project/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        implementation "androidx.activity:activity:1.3.1"
        implementation "androidx.fragment:fragment:1.3.6"
    }
}

如果你尝试同步你的项目,则会抛出异常。确保在各个 gradle 文件中添加依赖项:

// Project/app/build.gradle
dependencies {
    implementation "androidx.activity:activity:1.3.1"
    implementation "androidx.fragment:fragment:1.3.6"
}

可能的解决方案 #2(过时的 Gradle)

如何修复错误Could not find method implementation?在版本低于3.0的Gradle插件的配置中使用implementation指令时,将无法识别实现,因此会抛出异常。如果是这种情况,请将implementation改为compiletestImplementation改为testCompileandroidTestImplementation替换为androidTestCompile

// Project/app/build.gradle
dependencies {
    compile "androidx.activity:activity:1.3.1"
    compile "androidx.fragment:fragment:1.3.6"
}

可能的解决方案 #3(升级 Gradle)

Could not find method implementation解决办法:如果将指令从implementation降级到编译不是一个选项,你可以将 Gradle 升级到最新版本。为此,导航到你的项目树并查看 app,然后查看 Gradle Scripts 并找到该build.gradle文件(项目:app)。在此 Gradle 构建文件中,将类路径更新为最新版本的 Gradle 构建插件:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

更新类路径后,导航到你的应用程序,然后导航到 Gradle 脚本并选择gradle-wrapper.properties文件并将其更新distributionUrl到最新版本的 Gradle:

distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip

在此更改之后,你将需要同步你的项目,并且你应该能够使用implementation指令包含依赖项。

快乐编码❤️!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: