A simplified child module build.gradle.kts:
    plugins {
        id("com.android.library")
        kotlin("android")
    }
    android {
         androidComponents.beforeVariants { it: com.android.build.api.variant.LibraryVariantBuilder ->
              it.enabled = run {
                   // logic to calculate if
                   it.productFlavors[0].second == "flavor" && it.buildType == "debug"
              }
         }
    }
Is it possible to extract function for calculation of enabled state of buildVariant?
    fun calculateIsEnabled(lvb: com.android.build.api.variant.LibraryVariantBuilder): Boolean {
         return lvb.productFlavors[0].second == "flavor" && lvb.buildType == "debug"
    }
build.gradle.kts but I don't know how to access it from submodule and if it is possible at allbuildSrc module, but com.android.build.api.variant.LibraryVariantBuilder is undefined here because the plugin com.android.library is not present here and I think it is not allowed and/or meaninglessSo, the question is: where to declare a shared function that uses types defined in a gradle plugin and need to be accessible in all submodules of type android library?
After several tries I solved it:
buildSrc/build.gradle.ktsrepositories {
    google()
    mavenCentral()
}
plugins {
    `kotlin-dsl`
}
dependencies {
     // important: dependency only in simple string format!
     implementation("com.android.tools.build:gradle:7.2.0-alpha03")
}
buildSrc/src/main/kotlin/Flavors.ktimport com.android.build.api.variant.LibraryVariantBuilder
import com.android.build.api.variant.ApplicationVariantBuilder
private fun isFlavorEnabled(flavor1: String, buildType: String): Boolean {    
    return flavor1 == "flavor" && buildType == "debug"
}
fun isFlavorEnabled(lvb: LibraryVariantBuilder): Boolean {
    // productFlavors are pairs of flavorType(dimension) - flavorName(selectedFlavor)
    return lvb.run { isFlavorEnabled(productFlavors[0].second, buildType ?: "") }
}
fun isFlavorEnabled(avb: ApplicationVariantBuilder): Boolean {
    return avb.run { isFlavorEnabled(productFlavors[0].second, buildType ?: "") }
}
library/build.gradle.kts and app/build.gradle.ktsandroid {
    androidComponents.beforeVariants {
        it.enabled = isFlavorEnabled(it)
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With