Question

I have a question when it comes to flavors in Android Studio using Gradle... Consider the following:

You have 3 flavors of your build; Flavor1, Flavor2, and Flavor3.

All 3 flavors rely on the same file, call it MainActivity.java for simplicity. Also, all 3 flavors have their own defined Constants File, call it Constants.java.

Other than Constants.java, Flavor1 and Flavor2 rely on the same source code. Namely, Flavor1 and Flavor2 both use the following files from main, MainActivity.java and also another file, call it AnotherActivity.java for simplicity.

Now, Flavor3 uses MainActivity.java but on the other hand needs some extra customization and some changes to AnotherActivity.java.

File Structure:
src
-main
--java
---MainActivity.java
---AnotherActivity.java

-Flavor1
--java
---Constants.java
-Flavor2
--java
---Constants.java
-Flavor3
--java
---Constants.java
---AnotherActivity.java

Is there a way to accomplish this type of build dependency without getting a duplicate class file error in Android Studio using Gradle?

Thanks!

Best Regards, Christopher Steven

Was it helpful?

Solution

I have found that only resources get merged this way. Source files get merged into a single build path. You will need to copy your AnotherActivity.java to each flavor as you have done with Constants.java. Look to refactor your source a bit to reduce the duplication is the best you can do. You could probably accomplish this with an AbstractAnotherActivity.java in src/main/java that the others extend.

You will notice that when you select the build variant in Android Studio it will show you only the source from the selected variant in the package view.

OTHER TIPS

A class completely replaces another when using Gradle flavors (of the same name obviously). Best practice to avoid reusing code is to have all shared code in your MainActivity so you don't duplicate it (otherwise changes have to be made in multiple locations). Reference any additional code/overrides in your AnotherActivity class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top