无法获得 属性 'compileSdkVersion' 额外的属性扩展,因为它不存在 打开文件

Cannot get property 'compileSdkVersion' on extra properties extension as it does not exist Open File

我将从 GitHub 下载的项目作为模块导入到我的 Android Studio 项目中。 "Import module..." 向导工作正常,但是当 Adroid Studio 尝试重建项目时,它返回给我这个错误:

Cannot get property 'compileSdkVersion' on extra properties extension as it does not exist Open File

错误与导入模块的"build.gradle"文件中的这一行有关:

compileSdkVersion rootProject.compileSdkVersion

我尝试在项目 "build.gradle" 中添加 "ext" 部分,如下所示:

ext {
    compileSdkVersion 26
}

但是这样我收到一个新的错误:

Gradle DSL method not found: 'compileSdkVersion()' Possible causes: ... 

在 build.gradle 中,您需要在 android 标记下编写 compilesdkversion,如本例所示:

android { .. compileSdkVersion 26 // 26 is an example ..}

顺便说一下。您可以将该模块构建为库,然后将其作为 .aar 文件导入到您的项目中。

将您的 .gradle android 部分更改为此

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "your App id"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

在您的顶级文件中使用:

ext {
    compileSdkVersion = 26
}

在您的 module/build.gradle 文件中使用:

android {
  compileSdkVersion rootProject.ext.compileSdkVersion
  ...
}

另一种方式:

你的build.gradle顶级模块

ext {
    minSdk = 21
    targetSdk = 29
    compileSdk = 29
    buildTools = '29.0.3'
}

您在 app 模块中的 build.gradle

android {
    def buildConfig = rootProject.extensions.getByName("ext")

    compileSdkVersion buildConfig.compileSdk
    buildToolsVersion buildConfig.buildTools
    defaultConfig {
        minSdkVersion buildConfig.minSdk
        targetSdkVersion buildConfig.targetSdk
    }
    // ...
}