Gradle基本知识点与常用配置
def versionMajor = 1
def v7Version = ‘2.0.3.RELEASE’
问题:
gradle 里 def 方法为什么不能引用 def 的变量
在项目根目录的gradle.properties文件配置:
# 应用版本名称
VERSION_NAME=1.0.0
# 应用版本号
VERSION_CODE=100
# 支持库版本
SUPPORT_LIBRARY=24.2.1
使用格式:
android {
defaultConfig {
applicationId project.APPLICATION_ID // lib项目不需要配置这一项
versionCode project.VERSION_CODE as int
versionName project.VERSION_NAME
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
//这里注意是双引号
compile "com.android.support:appcompat-v7:${SUPPORT_LIBRARY}"
}
ext{
// Sdk and tools
minSdkVersion = 15
targetSdkVersion = 26
compileSdkVersion = 26
junitVersion = '4.12'
}
使用格式:
注意:声明变量时用单引号’’;但是在dependencies中引用,必须使用双引号;否则有警告。
defaultConfig {
applicationId "com.example.test"
minSdkVersion rootProject.ext.minSdkVersion
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.support:appcompat-v7:$rootProject.v7Version"
testImplementation "junit:junit:$rootProject.junitVersion"
}
在根目录下的 build.gradle 文件中声明 ext{ … } 时, 加上一个变量 var ,如:
ext {
var = [
minSdkVersion : 14,
targetSdkVersion : 25,
supportLibraryVersion: "25.2.0"
]
}
引用格式:
android {
defaultConfig {
versionCode 1
versionName var.version
}
......
}
dependencies {
compile "com.android.support:appcompat-v7:$var.supportLibraryVersion"
}
或者在根目录单独定义一个gradle配置,
ext {
// 用于编译的SDK版本
COMPILE_SDK_VERSION = 23
// 用于Gradle编译项目的工具版本
BUILD_TOOLS_VERSION = "24.0.2"
// 目标版本
APPCOMPAT_VERSION = 23
}
然后在根目录下的build.gradle文件中去引入配置文件:
apply from: "config.gradle"
也可以在module中直接引用(路径不一样):
apply from : '../config.gradle'
使用格式:
android {
compileSdkVersion rootProject.compileSdkVersion
buildToolsVersion rootProject.buildToolsVersion
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:cardview-v7:${APPCOMPAT_VERSION}"
}
注意:声明变量时用单引号’’;但是在dependencies中引用,必须使用双引号;否则有警告。
https://blog.csdn.net/gao_chun/article/details/58105089 (荐)
https://blog.csdn.net/u012982629/article/details/81121717