我试图从string.xml格式化一个字符串,以便将其重用于多个值。我遇到了一些问题,因为String还应该包含格式化程序使用的百分比符号。我已经尝试用它的unicode表示替换%符号,但这似乎不起作用:
<?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-string中以获得“新值为25%”作为格式化字符串?
感谢您的帮助。
堆栈跟踪:
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-- 谢谢您的帮助。正确的答案是
<string name="teststring">The new value if %1$s%%</string>
formatted =“false”不得设置。
答案 0 :(得分:32)
使用
<?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);
答案 1 :(得分:5)
你可以试试\%%
而不是%??
像,
<string name="teststring">The new value is \%%</string>
或者
<string formatted="false" name="teststring" >The new value is %</string>
答案 2 :(得分:5)
试试这个
<string name="teststring"> The new value is %1$s %% </string>
答案 3 :(得分:1)
检查一下,
<string name="teststring">The new value is %1$s %%</string>
String value = "25";
String formattedString = this.getResources().getString(R.string.teststring, mPageNumber);
答案 4 :(得分:1)
String value = "25";
String formattedString = "The new value is " + value + (char) 0x0025;
如果现在是Log.d(TAG,formattedString);它会记录
The new value is 25%
答案 5 :(得分:0)
像这样使用:
String str = context.getResources().getString(R.string.teststring);
String formattedString = String.format(str, value);
答案 6 :(得分:0)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="offerString">The new value is %1$s%% %2$s</string>
</resources>
String offerOnHdfc = "25";
String formattedString = String.format(getResources().getString(R.string.offerString), offerOnHdfc);
Log.i("",formattedString);