如何声明一个对所有模块的build.gradle文件可见的常量? [英] How to declare a constant that is visible to all modules' build.gradle file?

查看:269
本文介绍了如何声明一个对所有模块的build.gradle文件可见的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个模块的项目-库和应用程序.每次有新版本的Android出现时,我都需要为所有模块升级targetSdk,compileSdk,buildToolsVersion等.一个常数可以帮助完成这项繁琐的工作!

I have a project that has multiple Modules - libraries and applications. Everytime a new version of Android comes out, I need to upgrade the targetSdk, compileSdk, buildToolsVersion, etc. for all the modules. A constant could help with this tedious work!

如何定义对所有模块的build.gradle可见的项目级常量?

How could I define project-level constant that is visible to all module's build.gradle?

推荐答案

我选择执行类似操作的方法是创建一个属性文件,然后读取所有全局变量的内容.您可以使用Java语法做到这一点:

The way I choose to do something similar is to create a properties file and then just read that for all my global variables. You can do this with java syntax:

Properties props = new Properties()
props.load(new FileInputStream("/path/file.properties"))

更让人讨厌的语法是:

Properties props = new Properties()
File propsFile = new File('/usr/local/etc/test.properties')
props.load(propsFile.newDataInputStream())

这样,您可以在所有模块中重复代码,但至少可以解决您的问题.

That way, you may duplicate code in all your modules, but at least your problem is solved.

第二个选项是使用 ExtraPropertiesExtension 我个人从未使用过它,而是根据对问题 Android gradle build:如何设置全局变量的回答它似乎可以满足您的要求.

The second option is the use the ExtraPropertiesExtension I've personally never used it but according to the response to the question Android gradle build: how to set global variables it seems to do what you want.

更新

如果要使用ExtraPropertiesExtension执行此操作,请在<project base>/build.gradle中添加:

If order to do this using the ExtraPropertiesExtension, in your <project base>/build.gradle add:

allprojects {
    repositories {
        jcenter()
    }
    //THIS IS WHAT YOU ARE ADDING
    project.ext {
        myprop = "HELLO WORLD";
        myversion = 5
    }
}

然后在同步后,在每个模块的build.gradle文件中,您可以这样使用:

Then after a sync, in your build.gradle files for each module you can use this like so:

System.out.println(project.ext.myprop + " " + project.ext.myversion)

这篇关于如何声明一个对所有模块的build.gradle文件可见的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆