如何在build.gradle中获取资源值? [英] How to get a resource value in build.gradle?
问题描述
resValue
方法(或任何称为它的方法)使您可以设置在buildTypes
或productFlavors
中的资源值. 是否有相应的方法来获取由resValue
设置的资源值?
The resValue
method (or whatever it's called) allows you to set a resource value in buildTypes
or productFlavors
. Is there a corresponding way to get a resource value that was set by resValue
?
看来productFlavors
在buildTypes
之前被求值,所以在buildTypes
中设置的resValue
优先.我想在调试版本中将"Debug"附加到应用程序名称中,但是我需要获取在产品风格中设置的值才能附加到它.
It appears that productFlavors
is evaluated before buildTypes
, so a resValue
set in buildTypes
takes precedence. I want to append "Debug" to the app name in debug builds, but I need to get the value that was set in the product flavor in order to append to it.
我尝试了MarcinKoziński的建议使用变量,但在 any 构建类型之前先评估了 all 产品风味.因此,这不起作用:
I tried Marcin Koziński's suggestion to use a variable, but all product flavors are evaluated before any build type. Therefore, this does not work:
android {
String appName = ""
productFlavors {
Foo {
appName = "Foo"
}
Bar {
appName = "Bar"
}
}
buildTypes {
release {
resValue "string", "app_name", appName
}
debug {
resValue "string", "app_name", appName + " Debug"
}
}
}
在buildTypes
中,appName
始终具有来自 last 产品风味的值.因此,在此示例中,所有内部版本均使用名称"Bar"
或"Bar Debug"
.
In buildTypes
, appName
always has the value from the last product flavor. So in this example, all builds receive the name "Bar"
or "Bar Debug"
.
基本上,我需要一个类似于applicationIdSuffix
的resValueSuffix
.显然不存在这种动物. com.android.application
插件是否公开了我可以用来实现这一目标的任何东西?
Basically, I need a resValueSuffix
analogous to applicationIdSuffix
. Apparently no such animal exists. Does the com.android.application
plugin expose anything that I could use to achieve this?
推荐答案
If you are only trying to set the App Label (or other manifest values) you can solve this with manifest placeholders.
android {
productFlavors {
Foo {
applicationId "com.myexample.foo"
manifestPlaceholders.appName = "Foo"
}
Bar {
applicationId "com.myexample.bar"
manifestPlaceholders.appName = "Bar"
}
}
buildTypes {
release {
manifestPlaceholders.appNameSuffix =""
}
debug {
manifestPlaceholders.appNameSuffix =".Debug"
applicationIdSuffix ".debug"
}
}
}
然后,在您的Android清单中,您只需将两个占位符都用作您的应用名称(或其他值)
Then in your Android Manifest you simply use both placeholders for your app name (or other values)
<application
android:label="${appName}${appNameSuffix}"
...
</application>
这允许您将所有4个变体并排安装在单个设备上,并在应用程序抽屉/启动器中为它们指定不同的名称.
This allow you to install all 4 variants side by side on a single device as well as give them different names in the app drawer / launcher.
编辑,2019年11月22日
EDIT 11/22/2019
根据来自@javaxian的反馈更新了如何设置占位符值
Updated how placeholders values are set based on feedback from @javaxian
这篇关于如何在build.gradle中获取资源值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!