Android Studio: product flavor combination with more than two flavor dimensions (flavor groups)

You want to use same extra source directory for some flavors;

appleRedFree + appleRedPaid --> src/appleRed
pearRedFree + pearRedPaid --> src/pearRed
appleYellowFree + appleYellowPaid --> src/appleYellow
pearYellowFree + pearYellowPaid --> src/pearYellow

You can set sourceSet for your flavors:

android {

    // Other stuff here

    flavorDimensions "fruit", "color”, “version”

    productFlavors {

        apple {
            dimension "fruit"
        }
        pear {
            dimension "fruit"
        }

        red {
            dimension "color"
        }
        yellow {
            dimension "color"
        }

        free {
            dimension "version"
        }
        paid {
            dimension “version”
        }
    }

    sourceSets {
        appleRedFree {
            java.srcDirs = ['src/main/java', 'src/appleRed/java']
        }

        appleRedPaid {
            java.srcDirs = ['src/main/java', 'src/appleRed/java']
        }

        appleYellowFree {
            java.srcDirs = ['src/main/java', 'src/appleYellow/java']
        }

        appleYellowPaid {
            java.srcDirs = ['src/main/java', 'src/appleYellow/java']
        }

        pearRedFree {
            java.srcDirs = ['src/main/java', 'src/pearRed/java']
        }

        pearRedPaid {
            java.srcDirs = ['src/main/java', 'src/pearRed/java']
        }

        pearYellowFree {
            java.srcDirs = ['src/main/java', 'src/pearYellow/java']
        }

        pearYellowPaid {
            java.srcDirs = ['src/main/java', 'src/pearYellow/java']
        }
    }

   // Other stuff here
}

I have a little enhancement because I really don't like to copy/paste src sets :)

So you can do something like this:

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"
    }
}

I haven't tested it but it's based on my current implementation with additionally variant.buildType.name usage


Appendix - to set resource directory use

android.sourceSets."$srcSet".res.srcDirs = "src/$fruitColorSrcSet/res"