在安卓项目开发中,最常用的就是 gradle 配置,对于一个单一 module 来说,怎么配置其实影响不大。但是,如果存在多个 module,例如:
├── app
├── module1
├── module2
├── nodule3
├── module4
└── module5
那么这其中就涉及到各个 module 中 gradle 依赖的管理,如果管理不到位,就会出现重复包、不同版本包,甚至冲突等问题,那么如何做到版本统一呢?
常用方式如下:
1、新建 config.gradle,在里面定义 ext 信息,示例代码如下:
ext.deps = [
kt : [
core: "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
],
andX : [
core : 'androidx.core:core-ktx:1.2.0',
appcompat : 'androidx.appcompat:appcompat:1.1.0',
constraint: 'androidx.constraintlayout:constraintlayout:1.1.3',
livedata : 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0',
viewmodel : 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
],
google: [
material: 'com.google.android.material:material:1.1.0'
],
test : [
junit : 'junit:junit:4.12',
ext : 'androidx.test.ext:junit:1.1.1',
espresso: 'androidx.test.espresso:espresso-core:3.2.0'
]
]
2、通过 apply from: "config.gradle" 引入,使用 deps.andX.core 引入,便可以做到引用同一处定义信息,避免版本错乱问题。
到这里看起来像是问题解决了,那么...又来了一个新问题,如下图所示:
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
这几行代码有没有那么一丝丝的眼熟?应该、好像、大概、差不多、也许...每个 build.gradle 里面都要写一遍,哪怕引用 config.gradle 里面的同一配置,可是这几个重复的代码还是没有减少,那么...我们...能不能再优化一下呢,答案当然是肯定的啦。
3、在 config.gradle 中定义方法,在方法里面做引用聚合,这样就能减少重复代码了,show me code:
ext.baseDeps = { handler ->
handler.implementation deps.kt.core
handler.implementation deps.andX.core
handler.implementation deps.andX.appcompat
handler.implementation deps.andX.constraint
handler.implementation deps.andX.livedata
handler.implementation deps.andX.viewmodel
handler.testImplementation deps.test.junit
handler.androidTestImplementation deps.test.ext
handler.androidTestImplementation deps.test.espresso
}
相应的,build.gradle 里面的代码可以写成这样:
dependencies {
baseDeps(dependencies)
}
就是这样,一行代码即可搞定公共基础依赖,就是这么简单。
总结:
1. 配置 config.gradle 依赖组件/版本信息;
2. 提取组合依赖为一个方法;
3. 尽情一行代码调用吧;
最后,示例项目地址信息 示例代码,欢迎交流学习,如果错误,请指正。
网友评论