当项目模块化之后,会有很多个模块的 build.gradle 文件的配置是重复的。这样会导致一些统一的部分一旦修改就需要修改很多处,为了解决这种情况可以把统一的部分抽离出来,在需要的地方引入。代码如下:
新建一个 custom-build.gradle 文件
ext.setAppDefaultConfig = {apply plugin: 'com.android.application'setApplyDefaultConfig()setModuleDefaultConfig()setDepDefaultConfig()}ext.setLibDefaultConfig = {apply plugin: 'com.android.library'setApplyDefaultConfig()setModuleDefaultConfig()setDepDefaultConfig()}ext.setApplyDefaultConfig = {apply plugin: 'kotlin-kapt'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'}ext.setModuleDefaultConfig = {android {compileSdkVersion 29buildToolsVersion '29.0.2'defaultConfig {minSdkVersion 15targetSdkVersion 29versionCode 1versionName "1.0"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}dataBinding {// 开启 dataBindingenabled = true}}}ext.setDepDefaultConfig = {dependencies {implementation fileTree(include: ['*.jar'], dir: 'libs')implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"implementation "androidx.appcompat:appcompat:1.1.0"implementation "androidx.constraintlayout:constraintlayout:1.1.3"}}
实际应用如下:
apply from: "../custom-config.gradle"project.ext.setAppDefaultConfig()// 为 application 指定 applicationIdandroid {defaultConfig{applicationId "xxx.xxx.xxx"}}// 为 application 添加 xxx 依赖库dependencies {implementation "xxx.xxx.xxx"}
