AndroidStudio多个Module时dependencies的管理
在使用AndroidStudio做项目久了,会遇到同一个project下有多个module的情况,如果每个module同时又有相同的依赖、依赖相同的libary,(尤其是library)每次更新其版本都会是一件麻烦的事。现在通过集中管理依赖,对于一个proejct下多个module的情况来说是非常有用的。
假如你的project结构如下:
1 2 3 4 5 6 | root --module1 --build.gradle --module2 --build.gradle --build.gradle |
为了方便管理,我们在root目录下新建gradleDependency目录,此目录下新建dependencies.gradle文件,当然目录名称和gradle文件命名完全根据你的习惯来就可以了。新建完成后project结构如下:
1 2 3 4 5 6 7 8 | root --gradleDependency --dependencies.gradle --module1 --build.gradle --module2 --build.gradle --build.gradle |
这时在 dependencies.gradle 文件中加入如下内容(只是举例,具体根据自己项目情况):
1 2 3 4 5 6 7 8 9 10 11 12 13 | ext { //Version supportLibrary = '22.2.0' //libraries dependencies supportDependencies = [ design : "com.android.support:design:${supportLibrary}", recyclerView : "com.android.support:recyclerview-v7:${supportLibrary}", cardView : "com.android.support:cardview-v7:${supportLibrary}", appCompat : "com.android.support:appcompat-v7:${supportLibrary}", supportAnnotation : "com.android.support:support-annotations:${supportLibrary}", ] } |
说明:ext在这里相当于定义全局变量的意思
假如至此我们项目所依赖的library都已写在了 dependencies.gradle 中,这时在root目录下的build.gradle文件中要引入依赖:
1 2 | //download dependencies apply from 'gradleDependency/dependencies.gradle' |
这时,统一管理dependency的工作已经基本完成,最后一步就是在各个module中加入依赖了,比如在module1中要用到android-design的library,只需在module1下的build.gradle文件中添加 compile supportDependencies.design,如下:
1 2 3 4 5 | dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile supportDependencies.design } |
这样来管理依赖库是不是很🐂很方便呀!!!
2325