简体   繁体   中英

External reference/variable in build.gradle file

Is it possible to use some external reference or variable in build.gradle files?

I have several build.gradle files in my app source files, including the one for module app , module base , module player , etc. (it depends on the structure of your code and the names of your packages).

Inside of each of these files is the following or similar structure:

defaultConfig {
    minSdkVersion 23
    targetSdkVersion 28
    versionCode 1
    versionName "1.0.001"
}

Is there any way I can code this the way that I don't have to change these values in every file? Is it possible to use some external reference or variable and that way I can edit my versionCode , versionName , etc. just on one place?

In your Project gradle

ext {

    minSdkVersion = 14
    targetSdkVersion = 26
    compileSdkVersion = 26
    buildToolsVersion = '26.0.2'

    // App dependencies
    supportLibraryVersion = '26.1.0'
    mockitoVersion = '1.10.19'
    roomVersion = "1.0.0"
}

In your App gradle

    android {        
            compileSdkVersion rootProject.ext.compileSdkVersion
            buildToolsVersion rootProject.ext.buildToolsVersion

        defaultConfig {

        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
       .
       .

    }

        }

        dependencies {
            // App's dependencies, including test
            compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"

        }

You can define variables in top level build.gradle file and then reference these variables in each module's build.gradle - that way youll be changing them only once in one file.

to give you an example,this is top level file https://github.com/Ejstn/android-starter/blob/master/build.gradle and this one is module level file: https://github.com/Ejstn/android-starter/blob/master/app/build.gradle

You can also declare whole dependency as variable like in this google's app: https://github.com/google/santa-tracker-android/blob/master/build.gradle

Go to File/Project structure/app/flavors then you can get versionCode, versionName, etc then change them what you want and it effects all of your Files.

Check this Image

Yes it is.

In your project-level Gradle config (the one in the root of your project, outside any module folders), you can define variables under the buildscript block:

ext.thisVersionCode = 1
ext.thisVersionName = "1.0.001"

Then you should be able to reference them from your module-level configs:

defaultConfig {
    versionCode = rootProject.ext.thisVersionCode
    versionName = rootProject.ext.thisVersionName
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM