根据风味和构建类型构建要在代码中使用的 gradle 变量 [英] build gradle variables to be used in code depending on flavor AND build type
问题描述
有没有办法在我的代码中使用 build.gradle 中的变量,这取决于风味和 buildType?
Is there a way to use variables from build.gradle in my code, which is dependent on flavor AND buildType?
在此示例中:是否可以在 Gradle 中声明一个可在 Java 中使用的变量? 新的资源值仅取决于它是调试还是发布构建类型.
In this example here: Is it possible to declare a variable in Gradle usable in Java? the new resource value only depends on if its a debug or release build type.
我希望为每个可能的 buildVariant 设置一个变量.
What I would like to have is one variable for each possible buildVariant.
比如:
flavor1Debug => resValue "string", "app_name", "App 1 Debug"
flavor1Release => resValue "string", "app_name", "App 1"
flavor2Debug => resValue "string", "app_name", "App 2 Debug"
flavor2Release => resValue "string", "app_name", "App 2"
是否有一种很好的方法可以通过 build.gradle 或其他不包含开关或 if else 语句的方法来做到这一点?
Is there a nice way to do this either through build.gradle or another way that doesn't included switches or if else statements?
推荐答案
在您的应用程序的 build.gradle 中,实现此目的的一种方法是:
In build.gradle for your app, one way you could achieve this would be:
buildTypes {
debug {
productFlavors.flavor1.buildConfigField "String", "app_name", "\"App 1 Debug\""
productFlavors.flavor2.buildConfigField "String", "app_name", "\"App 2 Debug\""
}
release {
productFlavors.flavor1.buildConfigField "String", "app_name", "\"App 1\""
productFlavors.flavor2.buildConfigField "String", "app_name", "\"App 2\""
}
}
请注意,您需要在 buildTypes 之前定义 productFlavors{} 块.
Note that you'll want to define your productFlavors{} block before your buildTypes.
这篇关于根据风味和构建类型构建要在代码中使用的 gradle 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!