当项目模块化之后,会有很多个模块的 build.gradle 文件的配置是重复的。这样会导致一些统一的部分一旦修改就需要修改很多处,为了解决这种情况可以把统一的部分抽离出来,在需要的地方引入。代码如下:

新建一个 custom-build.gradle 文件

  1. ext.setAppDefaultConfig = {
  2. apply plugin: 'com.android.application'
  3. setApplyDefaultConfig()
  4. setModuleDefaultConfig()
  5. setDepDefaultConfig()
  6. }
  7. ext.setLibDefaultConfig = {
  8. apply plugin: 'com.android.library'
  9. setApplyDefaultConfig()
  10. setModuleDefaultConfig()
  11. setDepDefaultConfig()
  12. }
  13. ext.setApplyDefaultConfig = {
  14. apply plugin: 'kotlin-kapt'
  15. apply plugin: 'kotlin-android'
  16. apply plugin: 'kotlin-android-extensions'
  17. }
  18. ext.setModuleDefaultConfig = {
  19. android {
  20. compileSdkVersion 29
  21. buildToolsVersion '29.0.2'
  22. defaultConfig {
  23. minSdkVersion 15
  24. targetSdkVersion 29
  25. versionCode 1
  26. versionName "1.0"
  27. }
  28. buildTypes {
  29. release {
  30. minifyEnabled false
  31. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  32. }
  33. }
  34. dataBinding {
  35. // 开启 dataBinding
  36. enabled = true
  37. }
  38. }
  39. }
  40. ext.setDepDefaultConfig = {
  41. dependencies {
  42. implementation fileTree(include: ['*.jar'], dir: 'libs')
  43. implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
  44. implementation "androidx.appcompat:appcompat:1.1.0"
  45. implementation "androidx.constraintlayout:constraintlayout:1.1.3"
  46. }
  47. }

实际应用如下:

  1. apply from: "../custom-config.gradle"
  2. project.ext.setAppDefaultConfig()
  3. // 为 application 指定 applicationId
  4. android {
  5. defaultConfig{
  6. applicationId "xxx.xxx.xxx"
  7. }
  8. }
  9. // 为 application 添加 xxx 依赖库
  10. dependencies {
  11. implementation "xxx.xxx.xxx"
  12. }

参考链接如下:

参考链接 1