Skip to content Skip to sidebar Skip to footer

Android Studio Build Flavors - How To Have Same Source Files In Diverse Flavors

I need to create a demo flavor in android studio for an app. In my app level gradle file i have created another flavor called demo and the default flavor of full of course. It look

Solution 1:

I think you can't have same class in main flavor and your other flavor. you should just create another flavor, then move your Hello class from main flavor to that new flavor. this rule is just for .java files. I mean you can have an xml file in main flavor and another version in your custom flavor but you can't do this with java files.

here is a useful link with further explanation.

Solution 2:

I would advice to create 3 source sets:

  • main - which would contain common classes
  • demo - contains demo specific classes
  • pro - contains classes for pro versions

and declare them using:

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src/main/java']
        res.srcDirs = ['src/main/res']
        assets.srcDirs = ['src/main/assets']
    }
    pro {
        manifest.srcFile 'src/pro/AndroidManifestPro.xml'
        java.srcDirs = ['src/main/java', 'src/pro/java']
    }
    demo {
        manifest.srcFile 'src/oldlite/AndroidManifestDemo.xml'
        java.srcDirs = ['src/main/java', 'src/demo/java']        
    }
}

P.S. not really sure about syntax of java.srcDirs content - please double check yourself

Solution 3:

I was able to override classes but the key was not to include the class in my main folder.

So the fullDebug (i.e. main folder) build variant will never get run. Always run a flavor and not the main folder. The main folder will just be used to keep common things in it.

In my case I had a demo for USA and another country (demo and demo_us)and I needed two flavors. I'll always build for either of the two and won't build main.

enter image description here

From the image you can see I made all my package names to be the same: like com.example.******.myapplication. Since they all have the same package name in the MainActivity you just import Hello.java with that package name and it will pick the right variant at build time.

For resources it looks like it's different and it will override naturally but java class files have to do this way.

Post a Comment for "Android Studio Build Flavors - How To Have Same Source Files In Diverse Flavors"