androidgradleandroid-productflavorssource-sets

Android: Programmatically change SourceSet based on user settings


I am creating an app that has admin and user modes, and each mode has its own layouts, strings, and drawable resource files. I want to know how to change the resources SourceSet based on the app mode which can be toggled by the user at runtime.

Currently, I am using 2 product flavors to do this. But the problem with flavors is that it is build time, and I have to create 2 different apks, one for each flavor. So, being able to change SourceSet at runtime means I can have only 1 apk.

Update: I simply want a textview to call R.string.title, and this will call different string files based the user mode (Admin or user). This is the same as changing Locale language (en vs fr for example) will call the appropriate file without the need to change the code.


Solution

  • I want to know how to change the resources SourceSet based on the app mode which can be toggled by the user at runtime.

    That is not possible. Source sets are a compile-time construct. An APK contains the contents of source sets based on the build variant you chose when you compiled the APK — the contents of other source sets are not in that APK.

    I am creating an app that has admin and user modes, and each mode has its own layouts, strings, and drawable resource files.

    Then either those are two apps (and two APKs), or you need to have all of those resources in the one source set that goes into your one APK.

    Usually, an admin mode also involves dedicated Java/Kotlin code (e.g., dedicated fragments), and so just swapping resources would be insufficient, anyway.

    If you are distributing solely through the Play Store, you could look into using dynamic feature modules, if your concern is the size of the APK with both user and admin code/resources in it.