直捣黄龙!使用Version Catalog管理Android依赖

418 阅读1分钟

1.新建.toml文件

在项目根目录新建libs.versions.toml

image.png

okhttp为例

[versions]
okhttpVersion="4.9.1"

[libraries]
okhttp={module="com.squareup.okhttp3:okhttp",version.ref="okhttpVersion"}


[bundles]

2.导入

在项目根目录的settings.gradledependencyResolutionManagement下添加

versionCatalogs {
    create("libs") {
        // 从文件中导入,files别写错了
        from(files("$rootDir/libs.versions.toml"))
    }
}

image.png

3.使用

无需其他步骤app/build.gradle直接导入所需依赖,还是以okhttp为例

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation project(path: ':mylibrary')
    testImplementation 'junit:junit:4.13.2'
   
   
    implementation libs.okhttp

}

4.参考

遇到的错误警告,终于在StackOverFlow上找到:在 android studio 中从 BuildSrc 迁移到 Gradle 目录 -> “未知属性库” - 堆栈溢出 (stackoverflow.com)

Sharing dependency versions between projects (gradle.org)

将 build 迁移到版本目录  |  Android Studio  |  Android Developers