Android 在代码中使用 Gradle Build 风格,就像 if case [英] Android using Gradle Build flavors in the code like an if case
问题描述
我正在尝试使用构建风格.在我的 build.gradle 中,我定义了 2 种风格,一种是普通风格,一种是管理员风格.
I'm trying to work with build flavors. In my build.gradle I've defined 2 flavors, a normal flavor and an admin flavor.
基本上,管理员风格在主要活动上有一个额外的按钮.
Basicly, the admin flavor has an extra button on the main activity.
我知道我可以为不同的口味定义不同的包/类.但是有没有办法让 if case 根据风格添加/删除一段代码?
I understand that I can define different packages/classes for different flavors. But is there a way to make a sort of if case to add/remove a piece of code depending on the flavor?
基本上,我需要一个活动的两个版本.但我不想要活动的两个完全不同的版本并维护它们.
Basicly, I would need two versions of an Activity. But I don't want two entire different versions of the activity and maintain them.
所以在我的活动中我想做
So in my activity I would like to do
=>gradle 检查风味是否为管理员"
=> gradle check if flavor is 'admin'
=>如果是,添加按钮的这段代码
=> if yes, add this code of the button
这可能吗?或者您是否需要两种不同的体力活动,从而在之后添加功能时同时保持它们.
Is this possible? Or would you need two different physical activities and thus maintain both of them when you add functionality afterwards.
推荐答案
BuildConfig.FLAVOR
为您提供组合产品风味.因此,如果您只有一个风味维度:
BuildConfig.FLAVOR
gives you combined product flavor.
So if you have only one flavor dimension:
productFlavors {
normal {
}
admin {
}
}
然后你可以检查一下:
if (BuildConfig.FLAVOR.equals("admin")) {
...
}
但如果您有多个风味维度:
But if you have multiple flavor dimensions:
flavorDimensions "access", "color"
productFlavors {
normal {
dimension "access"
}
admin {
dimension "access"
}
red {
dimension "color"
}
blue {
dimension "color"
}
}
还有 BuildConfig.FLAVOR_access
和 BuildConfig.FLAVOR_color
字段,所以你应该像这样检查它:
there are also BuildConfig.FLAVOR_access
and BuildConfig.FLAVOR_color
fields so you should check it like this:
if (BuildConfig.FLAVOR_access.equals("admin")) {
...
}
并且 BuildConfig.FLAVOR
包含完整的风味名称.例如,adminBlue
.
And BuildConfig.FLAVOR
contains full flavor name. For example, adminBlue
.
这篇关于Android 在代码中使用 Gradle Build 风格,就像 if case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!