EricLarch EricLarch - 3 months ago 30
Android Question

Android plurals treatment of "zero"

If have the following plural ressource in my strings.xml:

<plurals name="item_shop">
<item quantity="zero">No item</item>
<item quantity="one">One item</item>
<item quantity="other">%d items</item>
</plurals>


I'm showing the result to the user using:

textView.setText(getQuantityString(R.plurals.item_shop, quantity, quantity));


It's working well with 1 and above, but if quantity is 0 then I see "0 items".
Is "zero" value supported only in Arabic language as the documentation seems to indicate?
Or am I missing something?

Answer

The Android resource method of internationalisation is quite limited. I have had much better success using the standard java.text.MessageFormat.

Basically, all you have to do is use the standard string resource like this:

<resources>
    <string name="item_shop">{0,choice,0#No items|1#One item|1&lt;{0} items}</string>
</resources>

Then, from the code all you have to do is the following:

String fmt = resources.getText(R.string.item_shop);
textView.setText(MessageFormat.format(fmt, amount));

You can read more about the format strings in the javadocs for MessageFormat

Comments