Quantity Strings (plurals)

When wanting to generate Strings that accommodate a range of numerical values, we need a way of determining the correct syntax according to the language. For example, in English we refer to ‘zero books’, ‘one book’ and ‘two (or more) books’. Android supports a set of options to cater for these variations, using the values: zero, one, two, few, many, other.

Methods such as getQuantityString can be used in conjunction with these options to provide the String you need to produce proper grammar. These are used exclusively for plurals and not for e.g. adding numerics to a String for information purposes: Inbox(12). Do not use quantity strings as a substitute for ‘if’ logic, as other languages handle grammatical rules differently.

It’s often possible to avoid quantity strings by using quantity-neutral formulations such as “Books: 1”. This makes your life and your translators’ lives easier, if it’s an acceptable style for your application.

The plurals can be stored in any xml resource file. It is the plurals element's name which Android identifies. The resource name is R.plurals.plural_name:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals
        name="plural_name">
        <item
            quantity=["zero" | "one" | "two" | "few" | "many" | "other"]
            >text_string</item>
    </plurals>
</resources>

As a working example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="numberOfSongsAvailable">
        <!--
             As a developer, you should always supply "one" and "other"
             strings. Your translators will know which strings are actually
             needed for their language. Always include %d in "one" because
             translators will need to use %d for languages where "one"
             doesn't mean 1.
          -->
        <item quantity="one">%d song found.</item>
        <item quantity="other">%d songs found.</item>
    </plurals>
</resources>

Associated Java:

int count = getNumberOfSongsAvailable();
Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);

When using the getQuantityString() method, you need to pass the count twice if your string includes string formatting with a number. For example, for the string %d songs found, the first count parameter selects the appropriate plural string and the second count parameter is inserted into the %d placeholder. If your plural strings do not include string formatting, you don't need to pass the third parameter to getQuantityString.