是否可以在 Gradle 中声明一个可在 Java 中使用的变量?

是否可以在 Gradle 中声明一个可在 Java 中使用的变量?基本上我想在 build.gradle 中声明一些变量,然后在构建时(显然)得到它.就像 C/C++ 中的预处理器宏...

Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time. Just like a pre-processor macros in C/C++...

声明的一个例子是这样的......:

An example of declaration would be something like that ... :

android {
    debug {
        A_VAR_RETRIEVABLE_IN_JAVA = 42
    }
    release {
        A_VAR_RETRIEVABLE_IN_JAVA = 42+52
    }
}

有没有办法做这样的事情?

Is there a way to do something like that ?

推荐答案

这里有两种从 Gradle 传递值以在 Java 中使用的方法;

Here are two ways to pass value from Gradle to use in Java;

android {
    buildTypes {
        debug {
            buildConfigField "int", "FOO", "42"
            buildConfigField "String", "FOO_STRING", ""foo""
            buildConfigField "boolean", "LOG", "true"
        }

        release {
            buildConfigField "int", "FOO", "52"
            buildConfigField "String", "FOO_STRING", ""bar""
            buildConfigField "boolean", "LOG", "false"
        }
    }
}

您可以使用 BuildConfig.FOO

android {
    buildTypes {
        debug{
            resValue "string", "app_name", "My App Name Debug"
        }
        release {
            resValue "string", "app_name", "My App Name"
        }
    }
}

您可以使用 @string/app_nameR.string.app_name

相关文章