Search code examples
javaandroidandroid-studioandroid-gradle-pluginandroid-productflavors

Creating flavor specific classes


I have created two Flavors for my Android app with package name com.test.flavors

I have created two flavors:

1) flavor1
2) flavor2

Now I'm trying to create flavor-specific classes for it: I have created the flavor1 folder under the src one, and under that I have created the package folder with name com.test.flavors.

So basically it is like this:

src--->|
       |----->flavor1 -->java-->com.test.flavors
       |
       |----->main --> All classes and resources as generally present
       |
       |----->flavor2 --> java-->This is where I cannot create the package directory

Now when I am trying to achieve the same thing for the flavor 2 I am not able to achieve it. After creating the java folder in flavor2 folder I am not able to create the package folder with the name com.test.flavors. Also the java folder in Android Studio viewer is blue for main as well as flavor1 where as for flavor2 it is not blue in color.

Can any one help me rectify the error?


Solution

  • To be able to compile files for a specific flavor, you have to:

    1. Include it into your build.gradle script.
    2. Click on Sync Project with Gradle Files.
    3. Switch to a build variant based on that flavor in the Build Variants panel (either ending with Debug or Release, even it the first one is the common choice while developing).

    This is pretty annoying, as you can't compile more than one build variant while you code. If you add a class to a flavor referencing it from the main code and forget to add it to the other flavors in the same flavor dimension, you will break them without seeing any error. You can always build more than one build variant from the Build > Generate Signed APK wizard though (on a Mac, just press cmd while you select all the variants you want to build), so some of the APKs may be built and others not.