Android复数形式无法正常工作,需要帮助。

14

我一直在尝试使用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的字符串。但当数量恰好为1时,它会正确计算为1 degree1 meter

提前感谢任何帮助!

敬礼,celestialorb。

3个回答

43

似乎需要两次指定count参数,第一次用于确定要使用的字符串,而第二次则是替换到该字符串中的数字。例如:

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

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


谢谢!终于让它工作了。这也意味着,如果你想要进行数据绑定,你需要指定两次值:android:text="@{@plurals/degrees(viewModel.temp_c, viewModel.temp_c)}" - Rubberduck

9

Android通过R.plurals支持使用复数形式,但实际上这个功能并没有详细的文档说明。深入源代码后发现,你可以有以下可能的字符串版本:

  • "zero"
  • "one"
  • "few"(仅适用于2)
  • "other"(适用于3及以上)

然而,我发现只有 "one" 和 "other" 实际上起作用(尽管其他字符串在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);

8
我可以补充一点,"zero"在英语中并不起作用,因为文档明确指出即使数量为0,在英语中表示零的字符串也将被忽略,因为0在语法上与2或任何其他数字(除了1)并没有区别。(http://developer.android.com/guide/topics/resources/string-resource.html#Plurals) - Fixpoint
2
@Shooshpanchick,谢谢 - 我不知道那个。但有点烦人,因为能使用“无匹配项”而不是“0匹配项”会更好。 - pheelicks

4
这里也有同样的问题!我猜这只是文档中的一个缺陷。 "纯粹"的getQuantitiyString(int, int)方法只获取文本资源,没有任何格式。正如superfell所说:只需使用getQuantityString(int, int, Object...)方法,并将整数值两次传递即可。
我曾希望它能像你做的那样工作,但它根本不行!
PS:也许选一个答案作为正确答案?;-)

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