Android多Flavor下不同applicationId及后缀配置问题
解决Android多Flavor下ApplicationId配置冲突问题
一、正确的Gradle配置方案
首先定义flavor维度,将target设为优先维度,再通过变体控制清除TargetB的customer后缀:
android { namespace "com.example.myapp" flavorDimensions "target", "customer" productFlavors { targetA { dimension "target" applicationId "com.example.myapp" } targetB { dimension "target" applicationId "com.example.myapp.targetb" } customerA { dimension "customer" applicationIdSuffix ".customera" } customerB { dimension "customer" applicationIdSuffix ".customerb" } } // 关键:针对TargetB变体清除customer维度的后缀 applicationVariants.all { variant -> def isTargetB = variant.flavors.any { it.name == "targetB" } if (isTargetB) { // 直接覆盖为TargetB自身的applicationId,忽略customer后缀 variant.applicationId = variant.productFlavors.find { it.dimension == "target" }.applicationId } } }
二、代码资源目录结构说明
要让customerA/customerB的代码资源同时适配targetA和targetB,只需保持标准的flavor目录结构即可,Gradle会自动合并对应维度的资源:
src/customerA/java/:customerA专属Java代码src/customerA/res/:customerA专属资源src/customerB/java/:customerB专属Java代码src/customerB/res/:customerB专属资源
不管是targetA-customerA、targetA-customerB还是targetB-customerA、targetB-customerB变体,都会自动加载对应customer目录下的内容。
三、为什么之前的配置失败
- 第一种配置未成功:默认情况下,Gradle会合并所有flavor维度的
applicationIdSuffix,TargetB没有显式清除customer维度的后缀,导致被叠加。 - 第二种配置未成功:可能是flavor维度顺序设置错误(比如把
customer设为优先维度),或者没有通过变体显式覆盖applicationId,导致Gradle自动拼接了所有维度的后缀。
内容的提问来源于stack exchange,提问作者alrama
相关产品推荐
相关产品推荐

