How to set different applicationId for each flavor combination using flavorDimensions when using Gradle Kotlin-DSL?

杀马特。学长 韩版系。学妹 提交于 2020-03-04 20:34:34

问题


I am converting an Android app to the Gradle Kotlin-DSL by using Kotlinscript files.

I have a problem converting our applicationId logic. We don't use the defaultConfiguration with applicationId plus various applicationIdSuffix for our flavors but a custom logic. The logic is described in this SO answer, here is the groovy code:

flavorDimensions "price", "dataset"

productFlavors {
    free { dimension "price" }
    paid { dimension "price" }
    dataset1 { dimension "dataset" }
    dataset2 { dimension "dataset" }
}

android.applicationVariants.all { variant ->
    def mergedFlavor = variant.mergedFlavor
    switch (variant.flavorName) {
        case "freeDataset1":
            mergedFlavor.setApplicationId("com.beansys.freeappdataset1")
            break
        case "freeDataset2":
            mergedFlavor.setApplicationId("com.beansys.freedataset2")
            break
        case "paidDataset1":
            mergedFlavor.setApplicationId("com.beansys.dataset1paid")  
            break
        case "paidDataset2":
            mergedFlavor.setApplicationId("com.beansys.mypaiddataset2")
            break
    }
}

With kotlin I cannot alter the applicationId of the mergedFlavor like in groovy. It is a val and therefore can't be changed.

Any elegant solution to solve this?


回答1:


I got help on the gradle Slack channel with this problem and the permission to share it here:

The trick is to cast the mergedFlavor to DefaultProductFlavor and than change the applicationId for it:

flavorDimensions("price", "dataset")

productFlavors {
    create("free") { dimension = "price" }
    create("pro") { dimension = "price" }
    create("dataset1") { dimension = "dataset" }
    create("dataset2") { dimension = "dataset" }
}

android.applicationVariants.all {
    val applicationId = when(name) {
        "freeDataset1" -> "com.beansys.freeappdataset1"
        "freeDataset2" -> "com.beansys.freedataset2"
        "proDataset1" -> "com.beansys.dataset1paid"
        "proDataset2" -> "com.beansys.mypaiddataset2"
        else -> throw(IllegalStateException("Whats your flavor? $name!"))
    }
    (mergedFlavor as DefaultProductFlavor).applicationId = applicationId
}

Any cleaner solution is appreciated!



来源:https://stackoverflow.com/questions/60103603/how-to-set-different-applicationid-for-each-flavor-combination-using-flavordimen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!