Technical docs‎ > ‎New Build System‎ > ‎

Resource Merging

The Gradle-base build system uses a new merging mechanism for resources. In previous build system, merging was done by passing a list of resource folders to aapt which acted as overlays, alongside the --auto-add-overlay to ensure that new resources in the overlays would be automatically added (default behavior is for overlays is to only override existing resources, not create new ones).

One of the goals of the Gradle-based build system was providing more flexibility, and one frequently asked feature request was the ability to have more than one resources folders. aapt is not able to handle this so the new build system introduces a new merging mechanism that is run ahead of aapt and generates a single, merged, resources folder that is fed to aapt. This merging has the advantage of being incremental, both through Gradle's input/output change detection, and in the way it is implemented (ie it can rerun the merge by only applying the change in a single file).

The merged resources are coming from 3 types of sources:
  • The main resources, associated with the main sourceSet, generally located in src/main/res
  • The variant overlays, coming from the Build Type, and Flavor(s).
  • The Library Project dependencies, which contribute resources through the res entry in their aar bundle.

Priority Order

The priority order is the following:

BuildType -> Flavor -> main -> Dependencies.

This means that if a resource is declared in both the Build Type and in main, the one from Build Type will be selected.

Note that for the scope of the merging, resources of the same (type, name) but different qualifiers are handled separately.

This means that if src/main/res has
  • res/layout/foo.xml
  • res/layout-land/foo.xml
and src/debug/res has
  • res/layout/foo.xml
Then the merged resource folder will contain the default foo.xml from src/debug/res but the landscape version from src/main/res

Handling Multiple Resource Folders

As mentioned above, each sourceSet can define multiple resource folders. For instance:

android.sourceSets {
   main.res.srcDirs = ['src/main/res', src/main/res2']
}

In this case, both resource folders have the same priority. This means that if a resource is declared in both folders, the merge will fail and an error will be reported.

Priority Order for Library Dependencies

With transitive dependencies, the actual set of Library Projects seen by a project is not a flat list but a graph. However the merging mechanism only handles a flat priority list.
If we consider the following example of dependencies:
Project -> A, B (meaning A higher priority than B)
A -> C, D
B -> C
The flat list passed to the merger will be A, D, B, C

This ensures that both A and B overrides C.