String Pluralization

15 Sep 2010 | Comments

Last week, I discovered Android’s support for plural strings by accident. And a good accident it was since I am working on an app that will display a float to the user. I used to display:

You set XX mile(s).

which is kinda lame.

Plurals lets you specify the string to display for different quantities. So how do we use this Plurals thing?

In your string resources XML, which is usually strings.xml, define the plurals element like so:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="pluralsTest">
   <item quantity="one">You have one friend.</item>
   <item quantity="other">You have %d friends.</item>
</plurals>
</resources>

Remember, your parent node must be <resources>!

Android provides several methods to use these in your code. Let’s see what each of them results to when used:

// set one as the quantity
String one = getResources().getQuantityString(R.plurals.pluralsTest, 1);

// set two as the quantity
String more = getResources().getQuantityString(R.plurals.pluralsTest, 2, 2);

// set one as the quantity
CharSequence quantity = getResources().getQuantityText(R.plurals.pluralsTest, 1);

// set two as the quantity
CharSequence quantityMore = getResources().getQuantityText(R.plurals.pluralsTest, 2);

I created a basic layout with TextViews to display what each of these strings look like. Take note though that getQuantityText() returns a CharSequence and not a String! Also, from what I have noticed, and as the name mildly suggests, getQuantityText() gets the actual value of the text you defined in your xml.