Search code examples
androidbuild.gradleandroid-build-flavors

Share Android.variantFilter for all app modules


I would like to use the same implementation for the android.variantFilter(...) for all my android apps modules.

Currently I have such a variantFilter in the "app"-Module which works fine:

android.variantFilter { variant ->
    String buildType = variant.buildType.name
    String flavor = variant.getFlavors().get(0).name

    if ((buildType == 'debug' && (flavor == 'canary' || flavor == 'int' || flavor == 'prd')) ||
            (buildType == 'release' && (flavor == 'dev' || flavor == 'loc')))
        variant.setIgnore(true)
}

The app contains several modules however and I would like to filter the variants in all modules likewise. Without having to reimplement the same variantFilter in all module's build.gradle files.

So my question is: is there a way to define that filter in a central place (for example the app's top level build.gradle file) and to cite it in the module specific build.gradle files?


Solution

  • Either put the script in a file called variants.gradle in the parent directory and apply it:

    apply from: '../variants.gradle'
    

    Or use AndroidComponentsExtension.beforeVariants

    At this stage, access to the DSL objects is disallowed, use finalizeDsl method to programmatically access the DSL objects before the VariantBuilderT object is built.

    and DslLifecycle.finalizeDsl (the only option available):

    API to customize the DSL Objects programmatically after they have been evaluated from the build files and before used in the build process next steps like variant or tasks creation.

    Which means, that variants can be programmatically configured, without declaring them explicitly. See this answer of mine... it's possibly not variant.setIgnore(true) but variant.enabled = false.