我一直在尝试使用Android的复数资源,但没有运气。
这是我的复数形式的资源文件:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<plurals name="meters">
<item quantity="one">1 meter</item>
<item quantity="other">
<xliff:g id="count">%d</xliff:g>
meters
</item>
</plurals>
<plurals name="degrees">
<item quantity="one">1 degree</item>
<item quantity="other">
<xliff:g id="count">%d</xliff:g>
degrees
</item>
</plurals>
</resources>
...然后这是我尝试从资源中提取数量字符串时使用的代码:
Resources res = this.getResources();
tTemp.setText(res.getQuantityString(R.plurals.degrees, this.mObject.temp_c.intValue()));
...但TextView中的文字仍然是%d degrees
和%d meters
。
有谁知道发生了什么?我调试了代码,res.getQuantityString(...)调用返回一个值为%d degrees
或%d meters
的String。虽然数量恰好为1,但却能正确评估1 degree
或1 meter
。
提前感谢您的帮助!
此致,celestialorb。
答案 0 :(得分:36)
您似乎需要指定两次计数,第一次用于确定要使用的字符串,第二次是替换为字符串的字符串。 e.g。
Resources res = this.getResources();
int tv = this.mObject.temp_c.intValue();
tTemp.setText(res.getQuantityString(R.plurals.degrees, tv, tv));
至少在我到目前为止的测试中,不需要资源中的xliff:g
元素。
答案 1 :(得分:4)
Android“支持”使用R.plurals复数的使用,这实际上没有记录。深入了解源代码表明您应该能够拥有以下可能的字符串版本:
然而,我发现只有“一个”和“其他”实际上有效(尽管其他人在android源码中使用!)。
要使用复数,您希望以与普通字符串资源类似的方式声明多个字符串:
<resources>
<plurals name="match">
<!-- Case of one match -->
<item quantity="one">1 match</item>
<!-- Case of several matches -->
<item quantity="other">%d matches</item>
</plurals>
</resources>
然后在代码中实际使用它们,使用类似于上面建议的superfell的代码:
String text = getResources().getQuantityString(R.plurals.match, myIntValue, myIntValue);
myTextView.setText(text);
答案 2 :(得分:3)
这里有同样的问题!我想这只是文档中的一个缺陷。 “纯”getQuantitiyString(int, int)
方法只获取文本资源,没有任何格式。正如superfell所说:只需使用getQuantityString(int, int, Object...)
方法并将整数值移交两次。
我希望这会像你一样工作,但它根本就没有!!
PS:也许检查答案是否正确? ; - )