I am building 4 different flavors of my Android app.
I have a class Customization.java
that is the same for 3 of them and different for 1.
Since I cannot put the same class both in the main folder and in the flavor folder, I now have to maintain 3 copies of the exact same class for those 3 flavors.
Is there any way that I could do with keeping just two versions of this class?
Things I have considered so far:
- I looked at flavor dimensions, but turns out they are not applicable in this case.
- Keeping just one file in one of the flavors and copying it through my build script.
I am wondering if there is something cleaner out of the box.
Best Answer
I would like to convert CommonsWare's comment to an answer. I'll then explain how the final directory setup should look like. I hope this helps out the people stumbling upon this question through search.
So, if the
Customization
activity's layout file is calledactivity_customization.xml
, you'll leave its common copy shared among the three flavors undersrc/main/res/layout
directory and place the modified layout xml to be used by, sayflavorFour
, under its corresponding source set directorysrc/flavorFour/res/layout
.The way this works is that since flavor one to three (unlike flavor four) haven't provided their own versions of
activity_customization.xml
, they'll inherit the one coming from themain
source set.Unlike resources, Java code files are not merged or overridden. So, you can't have Java files with the same fully qualified class name under
main
as well as in any of your flavor source sets. If you do, you'll receive a duplicate class error.To resolve this issue, the simplest solution is to move
Customization
activity out of themain
and into each flavor source set. This works because the flavor directories are mutually exclusive (with each other, not withmain
) hence avoiding the conflict.But this means three out of the four flavors have a duplicate copy of the activity - a maintenance nightmare - just because one of the flavors required some changes to it. To resolve this issue we can introduce another source directory that keeps just the common code files shared between the three flavors.
So, the
build.gradle
script would look something likeNotice the use of
java.srcDir
(and notsrcDirs
) which adds another Java source directory to the already existing defaultsrc/flavorX/java
.Now all we need to do is to drop the common
Customization
activity file insrc/common/java
to make it available to the flavors one to three. The modified version required byflavorFour
would go under its own source set atsrc/flavorFour/java
.So, the final project structure would look something like