問題描述
我正在嘗試使用構建風格.在我的 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_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 案例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!