Plurals in Android

Android supports Plurals. Plurals are XML based resources which allow to handle different quantities. This way you can select the right text based on the quantity. In your XML file you specify values for the quantities “zero”, “one”, “two”, “many”, “few”, “many”, “other” and in your code you use the method getQuantityString() to get the correct value. You can also format strings. If now Strings are formated then you pass in the plural resources and the number. If Objects should be used for formating you pass them as additional parameters.

For example the following will define a plural. This file needs to be in the “res/values” directory and in this example it is called “plurals”.

<?xml version="1.0" encoding="utf-8"?>
        <item quantity="zero">no Tutorial </item>
        <item quantity="one">one Tutorial </item>
        <item quantity="other">%d  Tutorials</item>

The correct value can then be select via the following coding:

// number is defined somewhere before this
// number =....
// Get the Resources
Resources res = getResources();
// Get the 
String quantityString = res.getQuantityString(R.plurals.tutorials,
	number, number);
// Do something with it...

From the Android development guide: Note that the selection is made based on grammatical necessity. A string for zero in English will be ignored even if the quantity is 0, because 0 isn’t grammatically different from 2, or any other number except 1 (“no tutorial”, “one tutorial”, “two tutorials”, and so on).

Thanks to mohammad dabbour and Kirill Grouchnikov for clarifying a question on this in Google+.

I hope this blog entry helps. You find me also on Twitter. My Google+ profile can be found Lars Vogels Profile.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Android. Bookmark the permalink.

4 Responses to Plurals in Android

  1. Zero tutorial*s* … really? 🙂

  2. Lars Vogel says:

    @Benjamin: Ah got it. Blog entry fixed.

  3. kmr says:

    According to german grammar it sounds familiar to me.
    After your post I googled for that, but it seems zero images, zero cars, zero tutorials is correct.

  4. Bill Angove says:

    Native English speaker here (but no experience of teaching English). The following are all valid sentences.

    “I have no tutorials.”
    “I have one tutorial.”
    “I have two tutorials.”

    “There is no tutorial.”
    “There are no tutorials.
    “There is one tutorial.”
    “There are two tutorials.”

    It depends on the context which plural format you would use for zero. It’s probably not worth worrying too much about it.

Comments are closed.