简体   繁体   中英

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

I have a custom task in my build.gradle which generates some string resources:

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.

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; did you mean to add the formatted="false" attribute?

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:

<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?

(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.

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

You can use % in xml

try this format \\%% in your xml

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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