OldSchool4664
OldSchool4664

Reputation: 1472

Gradle: Android Studio BuildType Resource Inheritance

All projects have a debug and release buildType by default. However often people will want to inherit from these base build types to make other build types with small differences. As we know the "initWith" function allows us to do this, which causes all Gradle configurations to be inherited. The problem is it does not appear to work for Android resources.

The use case for this is if you have debug vs release keys for various tools (ie need to be defined as strings), and you don't want to copy/paste strings.xml files across several different resource directories.

For example, let's say I have the following buildTypes:

If I then create resource directories:

The qa buildType will NOT have access to the debug strings.xml. I need to copy paste the strings.xml:

And of course, copy pasting is a real bad idea as any changes need to be made in every copy, and sooner or later a mistake will be made. I have tried changing "qa" to "qaDebug" and "debugQa" with no luck. I could use productFlavors, but then I would end up with way more different variants than I need, many of which aren't going to make any sense. For example, to have a dev, qa, and production build which share just the two base debug and release resource directories, I would need to define something like this:

Not only is the naming redundant, half of these build configs are unused. Multiply by the fact that I have a couple other inherited buildTypes than I am mentioning in this simplified example, and you can see it gets out of hand really quickly.

The other option is to define API keys as gradle variables (which I have currrently), but it's always better to use the standard approach to things as it ends up being tidier and new developers to the team can find things more easily. Also there are resources other than strings, ex google-services.json or even XML files, which can only be handled with resource directories.

Appreciate everyone's input.

Upvotes: 4

Views: 915

Answers (1)

user8230917
user8230917

Reputation:

You can specify a different source set for a build variant using sourceSets. In your case it should be as follows:

android {
   ...
   sourceSets {
        yourBuildVariant {
            res.srcDirs = ['app/src/debug/res']
        }
    }
}

Now yourBuildVariant res folder is "app/src/debug/res" instead of "app/src/yourBuildVariant/res".

To check the list of build variants and their related source sets, in Android Studio on the right side click on Gradle -> app -> Tasks -> android and click sourceSets twice.

Here is the Android documentation.

Upvotes: 3

Related Questions