Android 在代码中使用 Gradle Build 风格,例如 if 案例

时间:2023-02-13
本文介绍了Android 在代码中使用 Gradle Build 风格,例如 if 案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用构建风格.在我的 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.

基本上,admin 风格在主 Activity 上有一个额外的按钮.

Basicly, the admin flavor has an extra button on the main activity.

我知道我可以为不同的风格定义不同的包/类.但是有没有办法根据风格制作一种 if 案例来添加/删除一段代码?

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?

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

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 检查风味是否为 'admin'

=> 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 {
    }
}

然后你就可以检查它了:

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

还有 BuildConfig.FLAVOR_accessBuildConfig.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 案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Google 服务 3.0.0 缺少 api_key/current 密钥 下一篇:如何在 android studio 中启用 Jack (Java Android Compile

相关文章

最新文章