38

我使用复数来编译 Android 应用程序的数量字符串。我完全按照教程中可以找到的内容进行操作:

res.getQuantityString(
    R.plurals.number_of_comments, commentsCount, commentsCount);

以下是复数的定义:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="number_of_comments">
        <item quantity="zero">No comments</item>
        <item quantity="one">One comment</item>
        <item quantity="other">%d comments</item>
    </plurals>
</resources>

有趣的是,输出字符串与我定义的很奇怪:

commentsCount = 0 => "0 comments"  
commentsCount = 1 => "One comment"  
commentsCount = 2 => "2 comments"

我想这是因为文档说明When the language requires special treatment of the number 0 (as in Arabic).zero数量。有没有办法强制我的定义?

4

3 回答 3

63

根据文档

选择使用哪个字符串完全基于语法必要性。在英语中,即使数量为 0,0 的字符串也会被忽略,因为 0 在语法上与 2 或除 1 之外的任何其他数字(“零书”、“一本书”、“两本书”和很快)。

如果您仍想使用自定义字符串为零,您可以在数量为零时加载不同的字符串:

if (commentsCount == 0)
    str = res.getString(R.string.number_of_comments_zero);
else
    str = res.getQuantityString(R.plurals.number_of_comments, commentsCount, commentsCount);
于 2013-06-23T13:44:38.577 回答
3

复数是 Unicode 形式。这里的所有复数值。在英语中,零的复数形式,如 2、3,4,因此如果其他情况下,您必须使用其他字符串作为此值。

于 2014-04-21T07:53:02.480 回答
2

In Kotlin (thanks to Dalmas):

val result = commentsCount.takeIf { it != 0 }?.let {
    resources.getQuantityString(R.plurals.number_of_comments, it, it)
} ?: resources.getString(R.string.number_of_comments_zero)
于 2019-04-25T12:41:15.213 回答