Android build.gradle import flavors from another file

I put the Flavors product in a different file called other.gradle

and it looks like this:

project.ext.myflavors =  {
 mock {
     applicationId "com.mysite.mock"
 }

}

      

and I can successfully access the closure in my file build.gradle

like this:

myflavors()

      

but I am getting an error that the method layout is not defined.

Error:Gradle DSL method not found: 'mock()'

      

Can't you just define code from another file and import the code itself into an assembly file? Or how can I import flavors from another file?

+3


source to share


2 answers


It's great to refer to productFlavors

multiple times. So adding some or all of the flavors to the script included in your build script will work.

Create a Gradle script that contains logic that determines what flavor to add:

if (someCondition()) {
    android {
        productFlavors {
            one {
                applicationId = 'com.example.oneapp'
            }
        }
    }
} else {
    android {
        productFlavors {
            two {
                applicationId = 'com.example.twoapp'
            }
        }
    }
}

      



Now include this script from your build script. Reusing scripts is easy if you put it under a (subfolder) of the root project. For example:

apply from: rootProject.file('build-scripts/flavor-picker.gradle')

      

Note that your IDE may not notice the change in the script flavor selection or gradle.properties

, so if you make changes to them, you will probably have to manually reimport Gradle to see the correct set of tasks available.

+2


source


Assembly attributes can be defined in a separate file ( build_flavors.gradle

) as follows:

android {
    productFlavors {
        flavorA {
            // ...
        }
        flavorB {
            // ...
        }
    }
}

      



and then imported into build.gradle

:

apply plugin: 'com.android.application'
apply from: './build_flavors.gradle'

android {
    // the rest of your android configuration
}

      

+4


source







All Articles