安卓中如何显示百分号(%):字符串数组

5

我在strings.xml文件中有一个字符串数组,其中有多个项目。只有一个项目中有多个百分号“%”符号需要显示。似乎没有任何关于如何转义它的建议起作用。\%,\%\%或在string-array或items标签上使用formatted="false"。当我使用\%时,Eclipse会显示该项的错误,如果我使用\%\%,那么Eclipse就可以运行,但是文本会显示两个百分号“%%”。所以有什么办法可以在strings.xml中转义百分号“%”吗?

<string-array name="details">
     <item>Placement of things</item>
     <item>Percentage of times placed is 30% 
         and percentage of times release 50%</item>
</string-array>

显然,在string-array中转义多个百分号存在一个bug。我可以使用%一次,如果在同一项中使用多次,则会出现错误。 - JPM
奇怪,我可以完美地添加“%”,没有任何问题。您能解释一下您的代码具体是做什么的吗? - papachan
没有什么需要解释的,我想逐字显示这两个字符串。是Eclipse给了我错误提示,我无法编译。 - JPM
5个回答

3

您的ADT插件和SDK是否已经更新?我的已经更新并且没有显示这个错误。只需使用一个百分号就可以完美运行。

无论如何,您尝试将字符串放入CDATA中了吗?

<string-array name="details">
     <item>Placement of things</item>
     <item><![CDATA[Percentage of times placed is 30% 
             and percentage of times release 50%]]></item>
</string-array>

嗯,我遇到了错误,但我很确定我已经安装了最新的更新。在Eclipse中尝试使用CDATA方法也出现了错误,这似乎很奇怪。 - JPM

2
一个巧妙的方法是使用百分号的Unicode字符。
U+FE6A ﹪ small percent sign (HTML &#65130; )
U+FF05 % full-width percent sign (HTML &#65285;)

在XML中,您可以定义如下内容:
    <string-array name="details">
         <item>Placement of things</item>
         <item>Percentage of times placed is 30&#65130; 
             and percentage of times release 50&#65130;</item>
    </string-array>

维基百科上的百分号


1

我遇到了同样的问题,但是无论我尝试什么,在JB 4.1.2上都没有用。

以下是我尝试过的:

<string-array name="percentage">
    <item>a. 100%</item>            <!-- unknownFormatConversionException -->
    <item>b. 90&#37;</item>         <!-- unknownFormatConversionException -->
    <item>c. 80%%</item>            <!-- "somewhere" a double %% appears -->
    <item>d. 60\%</item>            <!-- no % appears -->
    <item>e. 40\%%</item>           <!-- unknownFormatConversionException -->
    <item>f. 30%\%</item>           <!-- unknownFormatConversionException -->
    <item><![CDATA[g. 20%]]></item> <!-- unknownFormatConversionException -->
    <item formatter="false>h. 10%</item>    <!-- unknownFormatConversionException -->
</string-array>

使用模拟器,我发现在ICS 4.0之前一切都很顺利,比如我的Galaxy-S GB 2.3.5,而在使用ICS及以上版本时,就会出现unknownFormatConversionExceptions,就像我的Nexus S JB 4.1.2一样。
最终,this是我的最终决定:完全省略百分号!
<item>a. 100</item>
<item>b. 90</item>
...

这只是一个非常粗略的解决方法,但至少我可以继续工作!

我正在使用ADT Build: v22.0.1-685705,在Ubuntu 13.04下运行
测试设备:Nexus S JB 4.1.2,三星Galaxy S GB 2.3.5


哇,这在更近期的安卓版本中仍然是个问题?嗯,这是三星的机子,他们总是做些不同寻常的事情。 - JPM

1

显然,使用旧版本的eclipse并且没有安装最新的android SDK会导致这个问题。我将eclipse升级到了3.6.2,并确保安装了最新版本的android sdk r10。希望这能帮助某些人并节省他们的时间,因为我浪费了几个小时来尝试修复/找到答案。

所以,这个问题的答案是,在字符串数组项中可以多次使用单个百分号而无需转义、重复或使用CDATA,只要您拥有最新版本的SDK和Eclipse。


尽管答案正确,但评分却是负数...不确定为什么会有人不同意,因为这就是解决方案。 - JPM

0
我的解决方法是在strings.xml中声明一个新的字符串,其中包含百分号并添加属性 formatted="false"
<string name="percents" formatted="false">10&#37; is not 20&#37;</string

然后在arrays.xml中

<string-array name="my_array">
    <item>@string/percents</item>
    ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接