I use plurals to compile a quantity string for an Android application. I follow exactly what one can find in the tutorials:

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

Here is the definition of the plurals:

<?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>

Interesting enough, the output string is odd to what I definied:

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

I guess this is because the docs state When the language requires special treatment of the number 0 (as in Arabic). for zero quantity. Is there any way to force my definition?

有帮助吗?

解决方案

According to the documentation :

The selection of which string to use is made solely based on grammatical necessity. In English, a string for zero will be ignored even if the quantity is 0, because 0 isn't grammatically different from 2, or any other number except 1 ("zero books", "one book", "two books", and so on).

If you still want to use a custom string for zero, you can load a different string when the quantity is zero :

if (commentsCount == 0)
    str = res.getString(R.string.number_of_comments_zero);
else
    str = res.getQuantityString(R.plurals.number_of_comments, commentsCount, commentsCount);

其他提示

Plural is Unicode form. all of plural value here. In English, plural for zero like 2, 3,4 so you must if else this value to use others string for this.

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top