13

我一直在尝试使用 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 degreesand %d meters

有谁知道发生了什么?我已经调试了代码, res.getQuantityString(...) 调用返回一个值为%d degreesor的字符串%d meters。尽管当数量恰好为 1 时,它确实正确地计算为1 degreeor 1 meter

提前感谢您的帮助!

问候,天体。

4

3 回答 3

41

看来您需要指定两次计数,第一次用于确定要使用的字符串,第二次是替换为字符串的那个。例如

Resources res = this.getResources();
int tv = this.mObject.temp_c.intValue();
tTemp.setText(res.getQuantityString(R.plurals.degrees, tv, tv));

至少在我到目前为止的测试xliff:g中,资源中的元素是不需要的。

于 2010-11-18T17:18:45.180 回答
9

Android 通过使用 R.plurals 来“支持”复数的使用,这实际上是无证的。深入研究源代码会发现您应该能够拥有以下可能的字符串版本:

  • “零”
  • “一”
  • “很少”(正好 2 个)
  • “其他”(3 岁及以上)

但是,我发现只有“一个”和“其他”真正起作用(尽管其他的在 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);
于 2010-12-10T22:28:40.787 回答
4

这里同样的问题!我想这只是文档中的一个缺陷。“纯”getQuantitiyString(int, int)方法只是获取文本资源,没有任何格式。正如 superfell 所说:只需使用该getQuantityString(int, int, Object...)方法并交出您的整数值两次。

我希望这和你一样,但它根本没有!

PS:也许检查一个答案是正确的?;-)

于 2011-03-20T11:05:40.933 回答