如何在 Kotlin Gradle DSL 中更新 applicationVariants 中的 manifestPlaceholders?

How to update the manifestPlaceholders in applicationVariants in Kotlin Gradle DSL?

我尝试将其转换为 Kotlin:

applicationVariants.all { variant ->
    def flavor = variant.productFlavors[0]
    def mergedFlavor = variant.getMergedFlavor()
    mergedFlavor.manifestPlaceholders = [applicationLabel: "${variant.buildType.appName[flavor.name]}"]
}

但是 manifestPlaceholder 是一个 val 并且不能被重新分配,所以这会导致错误:

applicationVariants.forEach {variant->
    val flavor = variant.productFlavors[0]
    val mergedFlavor = variant.mergedFlavor
    variant.mergedFlavor.manifestPlaceholders = mapOf("applicationLabel" to "${variant.buildType.appName[flavor.name]}")
}

通常我可以在 buildTypes 闭包中设置它,但我不能在这里这样做,因为 appName 是 buildTypes 中的一个映射,其中键是风格名称,所以 applicationLabel 取决于构建类型和味道。而且我认为您无法访问 buildTypes 中的风格,这就是您需要 applicationVariants 的原因。

我必须更改上面的一些内容才能使其正常工作:

  1. 风味图(此处为 appLabelMap)必须进入 applicationVariants,因此您可以直接使用它。
  2. ManifestPlaceHolders确实是一个val,但是你可以替换map中的值。 :)
  3. applicationVariants.forEach没有被执行,所以你必须使用applicationVariants.all。但请注意它与 koltin.collections.all() 有冲突(有点),因此您必须使用采取 Action 的闭包而不是闭包。

这是最终结果:

applicationVariants.all {
    val appLabelMap = when (this.buildType.name) {
        "debug" -> mapOf("flavorA" to "FlavorA Debug", "flavorB" to "FlavorB Debug")
        ...
        else -> mapOf("flavorA" to "FlavorA", "flavorB" to "FlavorB")
    }
    val flavor = this.productFlavors[0]
    this.mergedFlavor.manifestPlaceholders["applicationLabel"] = "${appLabelMap[flavor.name]}"
}

您还必须在 android.defaultConfig 中为 applicationLabel 设置默认值:

android.defaultConfig { manifestPlaceholders["applicationLabel"] = "FlavorA"}

这是AndroidManifest.xml的相关部分,以防万一不清楚:

<application
     android:label="${applicationLabel}"
     ...
     <activity
     ...>
     ...
     </activity>
     ...
</application>

一旦你知道怎么做,看起来很简单!

manifestPlaceHolders 在最近的 gradle 版本中更改为 val mutablemap

  manifestPlaceholders["appAuthRedirectScheme"] =  "whatever"
  manifestPlaceholders["appRedirectScheme"] =  "whatever"
    

这就是我的解决方法。