Gradle全局参数配置

96
飞奔的小马
2017.05.15 16:39* 字数 220
前言

当一个project下有多个module时,全局依赖参数可以统一起来,修改时只需修改一处就行了,比较方便。当然如果格式你看着不爽,可以不这样写,毕竟现在是社会主义社会嘛,选择自由。

配置

1.只想配置defaultConfig的情况和google系统的自带库
首先在项目的根build.gradle下配置ext

ext{
    compileSdkVersion =25
    buildToolsVersion= '25.0.2'
    minSdkVersion = 16
    targetSdkVersion = compileSdkVersion
    versionCode =1
    versionName ='1.0.0'
    supportLibVersion = '25.3.1'
}

然后在app/build.gradle下修改defaultConfig

    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        applicationId "com.xxx"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode rootProject.ext.versionCode
        versionName rootProject.ext.versionName
  
    }

dependencies {
       compile "com.android.support:design:$supportLibVersion"
       compile "com.android.support:cardview-v7:$supportLibVersion"
}

2.想配置defaultConfig和所有依赖库的情况
在项目的根目录下创建config.gradle文件

ext{
    android=[
            applicationId:"com.fsp.aiyagirl",
            compileSdkVersion :25,
            buildToolsVersion :"25.0.2",
            minSdkVersion : 16,
            targetSdkVersion : 25,
            versionCode : 1,
            versionName :"1.0.0"
    ]

    dependencies =[
            "appcompat-v7"        : "com.android.support:appcompat-v7:25.3.1",
            "constraint"        : "com.android.support.constraint:constraint-layout:1.0.2",
    ]
}

然后在根的build.gradle中引用
apply from: "config.gradle"
这样工程的所有module都能用这个文件的参数
最后在app/build.gradle中

android {
    compileSdkVersion rootProject.ext.android.compileSdkVersion
    buildToolsVersion rootProject.ext.android.buildToolsVersion
    defaultConfig {
        applicationId rootProject.ext.android.applicationId
        minSdkVersion rootProject.ext.android.minSdkVersion
        targetSdkVersion rootProject.ext.android.targetSdkVersion
        versionCode rootProject.ext.android.versionCode
        versionName rootProject.ext.android.versionName
     
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile rootProject.ext.dependencies["appcompat-v7"]
    compile rootProject.ext.dependencies["constraint"]
}

至此,配置工作已经全部结束,有不足之处可以提出来共同探讨。

Android
Web note ad 1