Problem:
Remove the same configuration under multiple modules
Solution:
Use allprojects or subprojects blocks inside the top-level gradle configuration file
Discuss:
When you create a new Android project in Android Studio, the IDE creates a two-level Gradle project, one in the root directory and one in the module directory called App. The top build.gradle have several blocks called Allprojects:
This block is gradle syntax, so it is not only available in adroid projects, but in all Gradle-based projects. The Allprojects property is derived from the properties of the class Org.gradle.api.Project in the Gradle project. This property consists of the current project and a collection of all the child items. There is also a method called this name, which allows you to configure the current project and all sub-projects.
PS: In Gradle API Middle age often has a property and method with the same name. The top and bottom questions will determine which one you are using.
The practice is to apply the closure parameters to each item in the Allprojects collection. That means you don't need to repeat repositories blocks in the subproject (app) because they already exist.
An alternative way is to use the subprojects block. For example, if you have multiple Android library items, each will be in the build File app library plugin. If each subproject is a class library project, you can remove the duplicate configuration by applying the plugin in the parent configuration, such as:
Subprojects returns a collection of sub-items and has a method called subprojects that uses closures for them.
Further thinking:
If you look at the documentation for the Allprojects method, you will find that this method uses a class called Org.gradle.api.Action to do the argument. The signature is as follows:
The document says this method executes the given action on the current project and on all sub-projects. Action<t> is a simple method called Execute that has only one parameter. It seems to imply that you want to create a class that implements the action interface, instantiate it, and use the struct as an argument. In Java before 1.8, this is often used as an anonymous inner class.
In groovy, you can simply use closures as parameters to implement a single-method interface. Closures can become a method implementation. Gradle the implementation of the allprojects and subprojects methods is to apply the closure parameters to each project.
Android Development: "Gradle Recipes for Android" reading notes (translation) 2.5--sharing configurations in projects