通常Android studio生成的gradle 项目都会有一个项目级别的build.gradle
文件、以及若干个module级别的 build.gradle
文件。
在app module的build.gradle
文件中我们可以使用如下的语句引入依赖
apply plugin: 'com.android.application' android { … } ... dependencies { compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.android.support:percent:23.4.0' compile 'com.android.support:cardview-v7:23.4.0' compile 'com.android.support:gridlayout-v7:23.4.0' compile 'com.google.android.gms:play-services-location:9.2.1' compile 'com.google.android.gms:play-services-gcm:9.2.1' ... }
|
痛点在于多次重复出现的版本号23.4.0
,9.2.1
,如果有多个module同时依赖了这些lib,
这个buidl version还将出现多次。
解决方案
通过如下的方法可以稍微改进一下
apply plugin: 'com.android.application' android { ... } ...
ext { supportLibraryVersion = '23.4.0' playServicesVersion = '9.2.1' } dependencies { compile "com.android.support:appcompat-v7:$supportLibraryVersion" compile "com.android.support:design:$supportLibraryVersion" compile "com.android.support:percent:$supportLibraryVersion" compile "com.android.support:cardview-v7:$supportLibraryVersion" compile "com.android.support:gridlayout-v7:$supportLibraryVersion" compile "com.google.android.gms:play-services-location:$playServicesVersion" compile "com.google.android.gms:play-services-gcm:$playServicesVersion" ... }
|
值得注意的地方有两点:
- 单引号
''
变成了""
- 通过
$
来引用属性值
groovy String参考链接 string interpolation
如果project中有多个module怎么办?
把ext
代码块移动到项目的build.gradle
中即可
buildscript { ... }
allprojects { ... } ...
ext { minSdkVersion = 14 targetSdkVersion = 23 compileSdkVersion = 23 buildToolsVersion = '23.0.2'
supportLibraryVersion = '23.4.0' playServicesVersion = '9.2.1' }
|
module中的build.gradle
如下
apply plugin: 'com.android.application' android { ... } ...
dependencies { compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion" compile "com.android.support:design:$rootProject.supportLibraryVersion" compile "com.android.support:percent:$rootProject.supportLibraryVersion" compile "com.android.support:cardview-v7:$rootProject.supportLibraryVersion" compile "com.android.support:gridlayout-v7:$rootProject.supportLibraryVersion"
compile "com.google.android.gms:play-services-location:$rootProject.playServicesVersion" compile "com.google.android.gms:play-services-gcm:$rootProject.playServicesVersion"
... }
|
注意一点就好 :用$rootProject.propority
来引用