Android 在代码中使用了类似于 if 的风格

我正在尝试制作口味。在我的 build.gradle 中,我定义了两种口味,一种是普通口味,另一种是管理口味。

基本上,管理风格有一个额外的按钮上的主要活动。

我知道我可以为不同的口味定义不同的包/类。但是,有没有一种方法可以根据代码的风味来创建一种 if 大小写来添加/删除代码呢?

基本上,我需要一个 Activity 的两个版本。但是我不想要两个完全不同版本的活动并维护它们。

所以我想在我的活动中

= > 分级检查味道是否为“管理”

= > 如果是,添加这个按钮的代码

这可能吗?或者您需要两种不同的物理活动,因此在以后添加功能时同时维护这两种活动。

42106 次浏览

BuildConfig.FLAVOR gives you combined product flavor. So if you have only one flavor dimension:

productFlavors {
normal {
}


admin {
}
}

Then you can just check it:

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"
}
}

there are also BuildConfig.FLAVOR_access and BuildConfig.FLAVOR_color fields so you should check it like this:

if (BuildConfig.FLAVOR_access.equals("admin")) {
...
}

And BuildConfig.FLAVOR contains full flavor name. For example, adminBlue.

To avoid plain string in the condition, you can define a boolean property:

productFlavors {
normal {
flavorDimension "access"
buildConfigField 'boolean', 'IS_ADMIN', 'false'
}


admin {
flavorDimension "access"
buildConfigField 'boolean', 'IS_ADMIN', 'true'
}
}

Then you can use it like this:

if (BuildConfig.IS_ADMIN) {
...
}

You can define either different build configuration fields or different resource values (like string values) per flavor, e.g. (as per Google's gradle tips and recipes), e.g.,

android {
...
buildTypes {
release {
// These values are defined only for the release build, which
// is typically used for full builds and continuous builds.
buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
resValue("string", "build_time", "${minutesSinceEpoch}")
...
}
debug {
// Use static values for incremental builds to ensure that
// resource files and BuildConfig aren't rebuilt with each run.
// If they were dynamic, they would prevent certain benefits of
// Instant Run as well as Gradle UP-TO-DATE checks.
buildConfigField("String", "BUILD_TIME", "\"0\"")
resValue("string", "build_time", "0")
}
}
}

So in this case, something like

productFlavors {
normal {
dimension "access"
buildConfigField("boolean", "IS_ADMIN", "false")
}


admin {
dimension "access"
buildConfigField("boolean", "IS_ADMIN", "true")
}
}

and then use it like

if (BuildConfig.IS_ADMIN) {
...
} else {
...
}

or if it is just to have different string values for different flavors, it can be done with different resValues and then you don't even need the if/then

You can try this way

   productFlavors {
def app_name = "you app name"
development {
versionCode 1
versionName "1.0.1"
buildConfigField 'String', 'varibalename', ""
}


release {
versionCode 1
versionName "1.0.1"
buildConfigField 'String', 'varibalename', ""
}
}

if(BuildConfig.varibalename){}