Android Studio build flavors - How to have same source files in diverse flavors

后端 未结 3 1079
后悔当初
后悔当初 2020-12-30 02:51

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.

相关标签:
3条回答
  • 2020-12-30 03:02

    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

    0 讨论(0)
  • 2020-12-30 03:22

    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.

    0 讨论(0)
  • 2020-12-30 03:27

    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.

    0 讨论(0)
提交回复
热议问题