Gradle Android Studio 中的错误:找不到 ID 为 'com.android.library' 的插件

Gradle Error in Android Studio: Plugin with id 'com.android.library' not found

当我尝试在 Android Studio 中构建 Android 库项目时,出现以下 Gradle 错误:

Gradle sync failed: Plugin with id 'com.android.library' not found.

我是 Gradle 的新手,这让我很困惑。为什么会这样?

build.gradle文件如下:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
}

假设您有一个如下所示的标准项目结构:

yourProject/
 + .idea/
 + gradle/wrapper/
 + lib-module/
    | build.gradle
 | build.gradle
 | gradlew
 | gradlew.bat
 | settings.gradle

您未能同步似乎表明您的 SDK/IDE 配置存在问题。

首先打开 "Project Structure" 对话框并确保 "Android SDK location:" 值设置为正确的路径。

其次,打开 SDK 管理器并再次确保您设置了正确的 SDK 位置路径。

第三,确认您安装了正确版本的 "Android SDK Build-Tools" 软件包。 (本例中为 23.0.2)

最后,为了验证我们没有任何不良状态,我建议从文件 -> "Invalidate Caches /Restart..."

中执行 "Invalidate and Restart"

完成所有这些后,我希望它应该同步。如果没有,请尝试从项目的根目录 运行 ./gradlew 并向我们更新任何新信息。

你的问题是你使用的是顶级文件,你不能在其中使用这种插件。

在 AS 中你有这样的结构:

Root/
 + lib
    | build.gradle
 | build.gradle
 | settings.gradle 

你的顶级文件中你可以使用:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

在您的 lib/build.gradle 中,您可以使用问题中发布的代码:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
}

终于在你的 settings.gradle

include ':lib'

也可以参考this question.

buildscript {
repositories {
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'    }
}

apply plugin: 'com.android.library'

将这些行添加到库的 gradle 文件中。

在我的案例中,是由于 local.properties 文件中的错误 sdk/ndk 路径,我将项目从一个 hd 移动到另一个,这些设置是错误的,修复路径解决了问题。