工程build.gradle文件的内容可以使用变量的形式定义
1.首先在根目录下创建文件:config.gradle,内容如下:
ext {
android = [
compileSdkVersion: 26,
buildToolsVersion: '27.0.3',
applicationId : "com.dzt.launchmode",
minSdkVersion : 15,
targetSdkVersion : 26,
versionCode : 1,
versionName : "1.0"
]
def dependVersion = [
support : "26.+",
retrofit : "2.1.0",
butterknife: "8.4.0",
blockcanary: "1.2.1",
leakcanary : "1.4-beta2"
]
dependencies = [
//base
"appcompat-v7" : "com.android.support:appcompat-v7:${dependVersion.support}",
"recyclerview-v7" : "com.android.support:recyclerview-v7:${dependVersion.support}",
"design" : "com.android.support:design:${dependVersion.support}",
]
}
此部分的dependVersion与dependencies可以自行添加。
2.在工程的build.gradle上添加
apply from: "config.gradle"
3.替换项目的build.gradle
替换前的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "27.0.3"
defaultConfig {
applicationId "com.dzt.launchmode"
minSdkVersion 15
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'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
替换后的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
defaultConfig {
applicationId rootProject.ext.android.applicationId
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile rootProject.ext.dependencies["appcompat-v7"]
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
此时如果有库版本更新、App版本号更新、添加新的库都可以通过config.gradle文件进行配置。