简体   繁体   English

使用resValue从build.gradle生成包含%的字符串资源

[英]Generate a string resource containing % from build.gradle with resValue

I have a custom task in my build.gradle which generates some string resources: 我的build.gradle中有一个自定义任务,它会生成一些字符串资源:

android.defaultConfig.resValue "string", "my_string", "Some Value"

This all works fine: the strings appear correctly in generated.xml and are accessible via getResources().getString(R.id.my_string) in the application code. 这一切都很好:字符串在generated.xml中正确显示,可以通过应用程序代码中的getResources().getString(R.id.my_string)访问。

It doesn't work when one of the strings contains a % symbol. 当其中一个字符串包含%符号时,它不起作用。 It gives this error: 它给出了这个错误:

Error:(1) Multiple substitutions specified in non-positional format; 错误:(1)以非位置格式指定的多个替换; did you mean to add the formatted="false" attribute? 你的意思是添加formatted =“false”属性?

I understand from Android XML Percent Symbol that one would normally work around this, for a string resource in strings.xml , by supplying the extra formatted="false" attribute as follows: 我从Android XML百分比符号中了解到,对于strings.xml中的字符串资源,通常会解决此问题,方法是提供额外的formatted="false"属性,如下所示:

<string formatted="false">My string with a % symbol</string>

How can I include the formatted="false" attribute when the string is generated using resValue in the build script? 在构建脚本中使用resValue生成字符串时,如何包含formatted="false"属性?

(I have also tried escaping with double-% as suggested, but that results in %% appearing in the final string.) (我也尝试使用双倍%来逃避,但这导致%%出现在最终字符串中。)

I solved it by replacing the raw % symbol with a double-escaped unicode value at string generation time in the gradle task. 我通过在gradle任务中的字符串生成时用双重转义的unicode值替换原始%符号来解决它。

android.defaultConfig.resValue "string", "my_string", \
    "String with a % symbol".replaceAll("%","\\\\u0025")

You can use % in xml 您可以在xml中使用%

try this format \\%% in your xml 在你的xml中尝试这种格式\\ %%

<string name="foo">percent symbol 50\%% </string> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM