Member-only story
The importance of being plural
Or how you can use quantity strings in Android
Through the years I often came into the request to fixing what seems a recurring issue:
<<The app shows “You have 1 unread messages” or worse “You have 0 unread messages” and we need to fix that in oder to show the correct message.>>
I’m pretty sure that everyone, at least once in their programmer life, asked ownself what would the proper way to handle this in code be.
To go back to the above example, based on the number of messages you could have: “no messages”, “1 message”, “2 messages” and so on.
Let’s see how to do this the right way in an Android app.
You can do it obviously by hand writing your code or by using what’s called “Quantity strings” or “plurals”.
Basically, what we can do in Android is to define different string resources based on the quantity (in particular, android supports zero
,one
, two
, few
, many
, and other
).
Plurals can be defined as android xml resources by using the <plurals> element as follows
and be retrieved via code by calling the getQuantityString method, passing in the quantity (you will need to pass the quantity twice if your string includes string formatting with a number).
Let us now see a practical example based on the problem shown at the beginning of the post.