本文介绍了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.

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

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

我知道我可以为不同的口味定义不同的包/类.但是,是否有一种方法可以根据口味来添加/删除一段代码呢?

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检查风味是否为管理员"

=> 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_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情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:40