product flavors, sources sets.Excluding files - android studio

2.8k Views Asked by At

I have an app with 4 product flavors. The build.gradle looks like this:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
defaultConfig {
    applicationId "com.example.testing"
    minSdkVersion 23
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
    flavor1 {
        applicationId "com.flavor1"
    }
    flavor2 {
        applicationId "com.flavor2"
    }
    flavor3 {
        applicationId "com.flavor3"
    }
    flavor4 {
        applicationId "com.flavor4"
    }
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

}

I have added the sourceSets for the flavors and added some files for each specific flavor.

Moreover I wanted to specify which files to exclude in flavor1 from the main sourceSet.

The files to exclude in the main sourceSet are in main/java/com/example/testing/ in there are

  • file1.java
  • file2.java
  • file3.java
  • file4.java

In each flavor I would like to exclude 1 file from these. But i want the flavor to have all the rest. Example:

flavor1 should have: file2, file3, file4.

falvor2 should have: file1, file3, file4.

etc.

As you can see the files are shared by most flavors so I don't want to put them all in the flavors cause it would be code replica and every change in every file would have to be applied to all the different flavor files.

I have seen this:

sourceSets {
    flavor1 {
        java {
            srcdir 'testing'
            exclude '/file1'
        }
    }

But it would not work for me. I cannot figure it out.

Thanks }

1

There are 1 best solutions below

0
On

A bit late, but may be useful for other users.

I think a good alternative is to put all your shared code (or resources) in one or more specific folders, lets say sharedfoo and use gradle to add them in any flavors that need it.

productFlavors {
    flavor1 {
      applicationId "com.flavor1"
    }
    flavor2 {
      applicationId "com.flavor2"
    }
    flavor3 {
      applicationId "com.flavor3"
    }
    flavor4 {
      applicationId "com.flavor4"
    }
}
sourceSets {
    flavor1 { java.srcDirs = ['src/flavor1/java', 'src/sharedfoo/java'] }
    flavor2 { java.srcDirs = ['src/flavor2/java', 'src/sharedfoo/java'] }
}