通過 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}"