通过 dependencies.gradle 文件集中依赖项

在处理多模块项目时,将依赖项集中在一个位置而不是将它们分布在许多构建文件中是有帮助的,尤其是对于常见的库(如 Android 支持库和 Firebase 库)

一种推荐的方法是分离 Gradle 构建文件,每个模块一个 build.gradle,项目根目录中的一个和依赖项的另一个,例如:

root
  +- gradleScript/
  |     dependencies.gradle
  +- module1/
  |     build.gradle
  +- module2/
  |     build.gradle
  +- build.gradle

然后,你的所有依赖项都可以位于 gradleScript/dependencies.gradle 中:

ext {
    // Version
    supportVersion = '24.1.0'

    // Support Libraries dependencies
    supportDependencies = [
            design:            "com.android.support:design:${supportVersion}",
            recyclerView:      "com.android.support:recyclerview-v7:${supportVersion}",
            cardView:          "com.android.support:cardview-v7:${supportVersion}",
            appCompat:         "com.android.support:appcompat-v7:${supportVersion}",
            supportAnnotation: "com.android.support:support-annotations:${supportVersion}",
    ]

    firebaseVersion = '9.2.0';

    firebaseDependencies = [
            core:         "com.google.firebase:firebase-core:${firebaseVersion}",
            database:     "com.google.firebase:firebase-database:${firebaseVersion}",
            storage:      "com.google.firebase:firebase-storage:${firebaseVersion}",
            crash:        "com.google.firebase:firebase-crash:${firebaseVersion}",
            auth:         "com.google.firebase:firebase-auth:${firebaseVersion}",
            messaging:    "com.google.firebase:firebase-messaging:${firebaseVersion}",
            remoteConfig: "com.google.firebase:firebase-config:${firebaseVersion}",
            invites:      "com.google.firebase:firebase-invites:${firebaseVersion}",
            adMod:        "com.google.firebase:firebase-ads:${firebaseVersion}",
            appIndexing:  "com.google.android.gms:play-services-appindexing:${firebaseVersion}",
    ];
}

然后可以从顶级文件 build.gradle 中的该文件应用,如下所示:

// Load dependencies
apply from: 'gradleScript/dependencies.gradle'

module1/build.gradle 一样:

// Module build file
dependencies {
    // ...
    compile supportDependencies.appCompat
    compile supportDependencies.design
    compile firebaseDependencies.crash
}

另一种方法

通过将版本号声明为变量一次并在任何地方使用它,可以实现集中库依赖关系版本的简洁方法。

在工作区 root build.gradle 中添加:

ext.v = [
    supportVersion:'24.1.1',
]

并且在使用相同库的每个模块中添加所需的库

compile "com.android.support:support-v4:${v.supportVersion}"
compile "com.android.support:recyclerview-v7:${v.supportVersion}"
compile "com.android.support:design:${v.supportVersion}"
compile "com.android.support:support-annotations:${v.supportVersion}"