随着 Android Gradle 插件(AGP)的不断更新,Gradle 构建脚本的写法也发生了变化。以下是新旧版本写法的详细对比:
1. 插件应用方式对比
旧版本写法 (AGP 3.x 及之前)
项目级 build.gradle:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
}
}
模块级 build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions' // Kotlin扩展插件
新版本写法 (AGP 4.0 及之后)
项目级 build.gradle:
// 可能完全省略buildscript,直接在settings.gradle中配置插件仓库
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
模块级 build.gradle:
plugins {
id 'com.android.application' version '7.2.1' // 版本号可选,推荐在settings.gradle中统一管理
id 'org.jetbrains.kotlin.android' version '1.7.0'
}
主要变化:
-
使用
plugins
块替代apply plugin
-
插件版本可以在
plugins
块中直接指定 -
插件仓库配置转移到
settings.gradle
的pluginManagement
块 -
Kotlin Android Extensions 已废弃,推荐使用 View Binding
2. 依赖配置对比
旧版本依赖配置
dependencies {
implementation 'androidx.appcompat:appcompat:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
// 动态版本号
implementation 'com.squareup.retr