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"?>
<resources>
<plurals
name="tutorials">
<item quantity="zero">no Tutorial </item>
<item quantity="one">one Tutorial </item>
<item quantity="other">%d Tutorials</item>
</plurals>
</resources>
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.
Zero tutorial*s* … really?
@Benjamin: Ah got it. Blog entry fixed.
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.
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.