Android XML百分比符号
-
08-10-2019 - |
题
我有一系列弦乐 %
使用符号。适当的格式用于使用 %
是 %
. 。当我在该数组中有一个带有多个字符串 %
它给了我这个错误。
Multiple annotations found at this
line:
- error: Multiple substitutions specified in non-positional format;
did you mean to add the formatted="false" attribute?
- error: Found tag </item> where </string-array> is expected
解决方案
Android资产包装工具(aapt
) 已经成为 最新版本非常严格 现在用于 全部 Android版本。您要获得的Aapt-Error,因为它不再允许 非位置格式指定符.
以下是一些想法,如何在资源字符串中包含%符号。
如果您不需要字符串中的任何格式指定符或替换,则可以简单地使用 formatted
属性并将其设置为 false
:
<string formatted="false">%a + %a == 2%a</string>
在这种情况下,该字符串不用作格式字符串 Formatter
因此,您不必逃脱自己的%符号。结果字符串为“%a +%a == 2%a”。
如果您省略了 formatted="false"
属性,该字符串用作格式字符串,您必须逃脱%符号。这是通过双%正确完成的:
<string>%%a + %%a == 2%%a</string>
现在 aapt
没有给您错误,但根据您的使用方式,结果字符串可以为“ %% A + %% A == 2 %% A”,如果A Formatter
被调用没有任何格式 参数:
Resources res = context.getResources();
String s1 = res.getString(R.string.str);
// s1 == "%%a + %%a == 2%%a"
String s2 = res.getString(R.string.str, null);
// s2 == "%a + %a == 2%a"
没有任何XML和代码,很难说出您的问题到底是什么,但希望这可以帮助您更好地理解机制。
其他提示
为了允许使用来自资源的格式字符串,您应该更正XML。所以,例如
<string name="app_name">Your App name, ver.%d</string>
应该替换
<string name="app_name">Your App name, ver.%1$d</string>
你可以看到 这个 有关详细信息。
您可以在XML解析器中使用%%逃脱%,但在设备中显示了两次。
要显示一次,请尝试以下格式: \%%
例如
<string name="zone_50">Fat Burning (50\%% to 60\%%)</string>
显示为Fat Burning (50% to 60%)
在设备中
利用
<string name="win_percentage">%d%% wins</string>
要得到
80% wins
作为格式的字符串。
我在用着 String.format()
获取数字而不是插入的方法 %d
.
在您的strings.xml文件中,您可以使用所需的任何Unicode符号。
例如,符号百分比的Unicode编号为0025:
<string name="percent_sign">%</string>
您可以看到一个全面的Unicode标志列表 这里
要逃脱百分比符号,您只需要%%
例如 :
String.format("%1$d%%", 10)
返回“ 10%”
不完全是您的问题,而是一个类似的问题。
如果您的字符串条目中有多种格式,则不应多次使用“%s”。
不 :
<string name="entry">Planned time %s - %s (%s)</string>
做 :
<string name="entry">Planned time %1$s - %2$s (%3$s)</string>
您可以使用%%逃脱XML中的%,但是您需要将文本设置为代码,而不是布局XML。
这可能是IDE变得过于严格的情况。
这个想法是正确的,通常您应该指定替换变量的顺序,以便您为另一种语言添加资源,您的Java代码无需更改。但是,有两个问题:
首先,诸如:
You will need %.5G %s
被用作 您将需要2.1200毫克 任何语言中的顺序都将与该质量数量相同,始终以科学的方式表示。
第二个是,如果将变量的顺序放在(例如英语)中指定的默认资源的任何语言中,那么您只需要指定语言资源字符串中的位置,将使用不同的顺序与默认语言使用不同的顺序。
好消息是,这很容易解决。即使无需指定职位,并且IDE过于严格,只要指定它们即可。对于上述示例,请使用:
您将需要%1 $ .5G%2 $ S
尝试这个(右):
<string name="content" formatted="false">Great application %s ☞ %s ☞ %s \\n\\nGo to download this application %s</string>
一种棘手的方法:使用以下的小百分比符号
<string name="zone_50">Fat Burning (50﹪ to 60﹪)</string>
根据Google官方文档,使用%1 $ s和%2 $ s http://developer.android.com/guide/topics/resources/string-resource.html#formattingandtingandstyling
您好,%1 $ S!您有%2 $ d新消息。
假设您想显示(50%的折扣)并在运行时输入50。这是代码:
<string name="format_discount"> (
<xliff:g id="discount">%1$s</xliff:g>
<xliff:g id="percentage_sign">%2$s</xliff:g>
OFF)</string>
在Java类中使用此代码:
String formattedString=String.format(context.getString(R.string.format_discount),discountString,"%");
holder1.mTextViewDiscount.setText(formattedString);
尝试在其前面使用后斜切,如下所示:
\%