通常Android studio生成的gradle 项目都会有一个项目级别的build.gradle文件、以及若干个module级别的 build.gradle文件。

在app module的build.gradle文件中我们可以使用如下的语句引入依赖

apply plugin: 'com.android.application'
android {

} ...
dependencies {
// support libraries
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'

//play services
compile 'com.google.android.gms:play-services-location:9.2.1'
compile 'com.google.android.gms:play-services-gcm:9.2.1'

// other dependencies
...
}

痛点在于多次重复出现的版本号23.4.09.2.1,如果有多个module同时依赖了这些lib,
这个buidl version还将出现多次。

解决方案

通过如下的方法可以稍微改进一下

apply plugin: 'com.android.application'
android {
...
}
...

ext {
supportLibraryVersion = '23.4.0'
playServicesVersion = '9.2.1'
}

dependencies {
// support libraries
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"

//play services
compile "com.google.android.gms:play-services-location:$playServicesVersion"
compile "com.google.android.gms:play-services-gcm:$playServicesVersion"

// other dependencies
...
}

值得注意的地方有两点:

  1. 单引号''变成了""
  2. 通过$来引用属性值

groovy String参考链接 string interpolation

如果project中有多个module怎么办?

ext代码块移动到项目的build.gradle 中即可

buildscript {
...
}

allprojects {
...
}
...

ext {
// sdk and tools
minSdkVersion = 14
targetSdkVersion = 23
compileSdkVersion = 23
buildToolsVersion = '23.0.2'

// dependencies versions
supportLibraryVersion = '23.4.0'
playServicesVersion = '9.2.1'
}

module中的build.gradle如下

apply plugin: 'com.android.application'
android {
...
}
...

dependencies {
// support libraries
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"

//play services
compile "com.google.android.gms:play-services-location:$rootProject.playServicesVersion"
compile "com.google.android.gms:play-services-gcm:$rootProject.playServicesVersion"

// other dependencies
...
}

注意一点就好 :用$rootProject.propority来引用