I have 2 flavors, lets say Vanilla and Chocolate. I also have Debug and Release build types, and I need Vanilla Release to have a field true, while the other 3 combinations should be false.
def BOOLEAN = "boolean"
def VARIABLE = "VARIABLE"
def TRUE = "true"
def FALSE = "false"
VANILLA {
debug {
buildConfigField BOOLEAN, VARIABLE, FALSE
}
release {
buildConfigField BOOLEAN, VARIABLE, TRUE
}
}
CHOCOLATE {
buildConfigField BOOLEAN, VARIABLE, FALSE
}
I'm having an error, so I guess the debug and release trick doesnt work. It is possible to do this?
BuildConfigField. Gradle allows buildConfigField lines to define constants. These constants will be accessible at runtime as static fields of the BuildConfig class. This can be used to create flavors by defining all fields within the defaultConfig block, then overriding them for individual build flavors as needed.
A build type determines how an app is packaged. By default, the Android plug-in for Gradle supports two different types of builds: debug and release . Both can be configured inside the buildTypes block inside of the module build file.
Creating Product Flavor is pretty much easy in Android Studio, we simply need to add productFlavors block inside the Android block in the application-level build. gradle file. It's that simple to create product flavors.
Build Type refers to build and packaging settings like signing configuration for a project. For example, debug and release build types. The debug will use android debug certificate for packaging the APK file. While, release build type will use user-defined release certificate for signing and packaging the APK.
Loop the variants and check their names:
productFlavors {
vanilla {}
chocolate {}
}
applicationVariants.all { variant ->
println("Iterating variant: " + variant.getName())
if (variant.getName() == "chocolateDebug") {
variant.buildConfigField "boolean", "VARIABLE", "true"
} else {
variant.buildConfigField "boolean", "VARIABLE", "false"
}
}
Here is a solution without lacks I've described under Simas answer
buildTypes {
debug {}
release {}
}
productFlavors {
vanilla {
ext {
variable = [debug: "vanilla-debug value", release: "vanilla-release value"]
}
}
chocolate {
ext {
variable = [debug: "chocolate-debug value", release: "chocolate-release value"]
}
}
}
applicationVariants.all { variant ->
def flavor = variant.productFlavors[0]
variant.buildConfigField "boolean", "VARIABLE", "\"${flavor.variable[variant.buildType.name]}\""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With