In Gradle, is it possible to create a boolean build config field based on another build config field?
It's not pretty, but it worked for me:
android {
...
defaultConfig {
...
buildConfigField "boolean", "A", "false"
buildConfigField "boolean", "B", "false"
println "value of A:" + buildConfigFields.get("A").value
println "value of B:" + buildConfigFields.get("B").value
boolean AandB = Boolean.valueOf(buildConfigFields.get("A").value) && Boolean.valueOf(buildConfigFields.get("B").value)
println "value of AandB:" + AandB
buildConfigField "boolean", "C", String.valueOf(AandB);
println "value of C:" + buildConfigFields.get("C").value
}
}
When you build the project, you should see this in the Android Studio gradle console:
A value: false
B value: false
AandB value: false
C value: false
I suppose the reason for this has nothing to do with the fact that the content inside the closure of the default configurationConfig becomes delegated to the ProductFlavor instance, which extends DefaultProductFlavor, which extends BaseConfigImpl, which contains the public getBuildConfigFields method.
However, I don't see "getBuildConfigFields" being officially documented as a method on ProductFlavor , and I'm worried that this may not always be available for our use.
Also note that buildConfigFields.get () gives you an instance of the ClassField class:
public interface ClassField {
@NonNull
String getType();
@NonNull
String getName();
@NonNull
String getValue();
@NonNull
String getDocumentation();
@NonNull
Set<String> getAnnotations();
}
hence, you need to get its value and convert it from String to Boolean by calling Boolean.valueOf ().
source to share
This code, written inside the block android.defaultConfig
, does exactly that:
buildConfigField("boolean", "TEST_A", "false");
buildConfigField("boolean", "TEST_B", "false");
buildConfigField("boolean", "TEST_C", "TEST_A && TEST_B");
This will result in the following lines in BuildConfig.java
:
public static final boolean TEST_A = false;
public static final boolean TEST_B = false;
public static final boolean TEST_C = TEST_A && TEST_B;
It is interesting to note that when declaring assembly configuration values ββthis way, if you look at how the structure is structured BuildConfig.java
, you can see that fields declared in a particular assembly type (for example android.buildTypes.debug
) appear before fields declared in the default configuration.
So in the above example, if you want to TEST_C
depend on the actual type of the assembly, you need to declare TEST_A
and TEST_B
on type of assembly level, instead of at the default level.
source to share