Jose Gómez
Jose Gómez

Reputation: 3224

Android Studio: product flavor combination with more than two flavor dimensions and build type

When working with more than 2 flavors, ADT/gradle doesn't currently support overriding with a subset of the flavors.

i.e. I have flavors apple/orange, red/green, bad/good. Then I can have resource/java folders as:

apple
orange
appleRedBad
orangeRedGood

But by default it is not possible to have

appleRed

One has to create all possible combinations, copying the files.

This was previously discussed, and the following solution was proposed, which works great:

android {
    …
    applicationVariants.all { variant ->
        def flavors = variant.productFlavors
        def fruit = flavors[0].name
        def color = flavors[1].name
        def version = flavors[2].name

        def fruitColorSrcSet = fruit + color.capitalize()
        def srcSet = fruitColorSrcSet + version.capitalize()
        android.sourceSets."$srcSet".java.srcDirs += "src/$fruitColorSrcSet/java"
        android.sourceSets."$srcSet".res.srcDirs += "src/$fruitColorSrcSet/res"
    }
}

However, I have some resource folders which are specific to the Release or Debug builds. E.g. "appleYellowDebug". I have tried adding variant.buildType.name to the source dir, but then since I'm still using the same android.sourceSets."$srcSet".java.srcDirs for both build type, the folder gets added to both debug and release builds:

android.sourceSets."$srcSet".java.srcDirs += "src/$fruitColorSrcSet" + variant.buildType.name.capitalize() + "/java"

How can I add a folder only to a release or debug source set? Is that possible at all? Right now I am adding each of the flavors+build types to the source set, but this is very verbose; I'd rather add it in a generic form as per above.

Upvotes: 1

Views: 845

Answers (1)

Jose Gómez
Jose Gómez

Reputation: 3224

I've managed to find the solution, which is just that the build types add new source sets, such as appleRedDebug. So all I had to do was to add the resource folder to android.sourceSets."$srcSetBuildType", as in:

android {
    …
    applicationVariants.all { variant ->
        def flavors = variant.productFlavors
        def fruit = flavors[0].name
        def color = flavors[1].name
        def version = flavors[2].name

        def fruitColorSrcSet = fruit + color.capitalize()
        def srcSet = fruitColorSrcSet + version.capitalize()

        // flavor combinations
        android.sourceSets."$srcSet".java.srcDirs += "src/$fruitColorSrcSet/java"
        android.sourceSets."$srcSet".res.srcDirs += "src/$fruitColorSrcSet/res"

        // flavor + build type combinations
        def buildType = variant.buildType.name
        def srcSetBuildType = fruitColorSrcSet + version.capitalize() + buildType.capitalize()
        android.sourceSets."$srcSetBuildType".res.srcDirs += "src/$fruitColorSrcSet" + buildType.capitalize() + "/res"
    }
}

Upvotes: 0

Related Questions