Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add build flavor from within a custom Gradle plugin

I'm writing a custom Gradle plugin which will add one or more tasks to an Android project. One of the tasks needs to add an 'ad hoc' build flavor to the list of existing build flavors already defined by the Android project.

I've tried altering one of the existing build flavors by changing the name as shown by the following code:

import com.android.build.gradle.internal.dsl.ProductFlavor
import org.gradle.api.Plugin
import org.gradle.api.Project

class MyPlugin implements Plugin<Project> {

    @Override
    void apply(Project target) {
        ProductFlavor adHocFlavor = target.android.productFlavors.first()
        adHocFlavor.name = 'adHoc'
        target.android.productFlavors.add(adHocFlavor)
    }

}

The problem here is that all build flavors in target.android.productFlavors are read-only at this point and throws the following error:

Cannot set the value of read-only property 'name' for ProductFlavor_Decorated

Does anyone have any idea how I can dynamically add a build flavor from within the plugin?

like image 790
SolveSoul Avatar asked Jan 21 '26 01:01

SolveSoul


1 Answers

It should be as simple as this:

@Override
void apply(Project target) {
    target.android.productFlavors.create("name")    
}

productFlavors is an instance of NamedDomainObjectContainer.

From docs of NamedDomainObjectContainer.create():

Creates a new item with the given name, adding it to this container.

Thus, this will create a ProductFlavor with provided name and it to productFlavors.

like image 175
azizbekian Avatar answered Jan 22 '26 15:01

azizbekian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!