使用gradle的自定义Property实现Android项目的配置和依赖统一管理

来源:互联网 发布:win10 mysql卸载 编辑:程序博客网 时间:2024/05/22 14:03

gradle支持自定义property,在GoogleSamples中官方用了Ext(ra) Properties方式来定义了Android的配置文件和统一的依赖管理,这种方式也称动态属性,我们必须使用关键字ext(对应ExtraPropertiesExtension的实例)来定义动态属性

在project根目录的build.gradle文件里使用如下配置:

ext {    //Android configs    configs = [            applicationId    : "com.example.application",            compileSdkVersion: 25,            buildToolsVersion: '25.0.2',            minSdkVersion    : 17,            targetSdkVersion : 25,            versionCode      : 17,            versionName      : '3.1.5'    ]    // App dependencies    supportLibraryVersion = '25.1.0'    junitVersion = '4.12'    multidexVersion = '1.0.1'    gsonVersion = '2.4'    ......}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

configs里定义了Android项目的配置信息,configs下面定义的则是依赖配置信息

在app(module)目录下的build.gradle文件中使用如下配置:

android {    compileSdkVersion configs.compileSdkVersion    buildToolsVersion configs.buildToolsVersion    defaultConfig {        applicationId configs.applicationId        minSdkVersion configs.minSdkVersion        targetSdkVersion configs.targetSdkVersion        versionCode configs.versionCode        versionName configs.versionName    }    ......}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在android节点下可以使用configs.xxxxxx方式来配置sdk tools 版本信息等等

dependencies {    testCompile "junit:junit:$rootProject.junitVersion"    compile "com.google.code.gson:gson:$rootProject.gsonVersion"    //MaterialDesign    compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"    compile "com.android.support:design:$rootProject.supportLibraryVersion"    //CardView    compile "com.android.support:cardview-v7:$rootProject.supportLibraryVersion"    //RecyclerView    compile "com.android.support:recyclerview-v7:$rootProject.supportLibraryVersion"    ......
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在dependencies节点下可以使用$rootProject..xxxxxx方式来配置依赖信息
使用这种方式的好处是当Android Support Repository有更新时
可以直接在gradle文件中展现提示,又有提示,又能统一管理依赖版本号,一举两得
这里写图片描述

参考:
http://www.blogjava.net/wldandan/archive/2012/07/05/382246.html
https://github.com/googlesamples/android-architecture/blob/todo-mvp/todoapp/build.gradle

转自:http://blog.csdn.net/lj402159806/article/details/54933679