strings.xml中的百分比符号 [英] percentage symbol in strings.xml
问题描述
我正在尝试格式化来自string.xml的字符串,以将其与多个Values一起使用.我遇到了一些问题,因为字符串还应该包含格式化程序使用的百分比符号.我已经尝试用其unicode表示形式替换%符号,但这似乎不起作用:
Im trying to format a string from string.xml to reuse it with several Values. I'm running into some problems as the String should also contain the percentage-symbol which is used by the formatter. I already tried to replace the % symbol by its unicode presentation but that doesnt seem to work:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="teststring">The new value is %1$s%</string>
<string name="teststring2">The new value is %1$s\u0025</string>
<string name="teststring3">The new value is %1$s</string>
</resources>
Java代码:
String value = "25";
String formattedString = context.getResources().getString(R.string.teststring), value);
在此示例中. teststring和teststring2将产生错误,而teststring3可以正常工作.将那个%符号放在xml字符串中以获得格式化字符串的新值是25%"的正确方法是什么?
In this example. teststring and teststring2 will produce an error, while teststring3 works fine. Whats the correct way to put that % symbol in the xml-string to get "The new value is 25%" as formatted String?
感谢您的帮助.
Stacktrace:
Stacktrace:
FATAL EXCEPTION: main
java.util.UnknownFormatConversionException: Conversion:
at java.util.Formatter$FormatSpecifierParser.unknownFormatConversionException(Formatter.java:2304)
at java.util.Formatter$FormatSpecifierParser.advance(Formatter.java:2298)
at java.util.Formatter$FormatSpecifierParser.parseConversionType(Formatter.java:2377)
at java.util.Formatter$FormatSpecifierParser.parseArgumentIndexAndFlags(Formatter.java:2348)
at java.util.Formatter$FormatSpecifierParser.parseFormatToken(Formatter.java:2281)
at java.util.Formatter.doFormat(Formatter.java:1069)
at java.util.Formatter.format(Formatter.java:1040)
at java.util.Formatter.format(Formatter.java:1009)
at java.lang.String.format(String.java:1988)
at android.content.res.Resources.getString(Resources.java:343)
at (... and so on)
-编辑- 谢谢您的帮助.正确答案是
--EDIT-- Thanks for the Help. The correct answer is
<string name="teststring">The new value if %1$s%%</string>
不得设置
formatted ="false".
formatted="false" must not be set.
推荐答案
使用
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="teststring">The new value is %1$s%%</string>
</resources>
在Java中
String value = "25";
String formattedString =
String.format(getResources().getString(R.string.teststring), value);
Log.i("",formattedString);
这篇关于strings.xml中的百分比符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!