If you are writing an app, that uses a string containing numbers, for example:
Deleted 1 message
Deleted 2 messages
You could manually create two different strings, and show either one by using an if/else, depending on the number variable.
However, as you start internationalizing your app, by adding more translations, this quickly gets out of hand!
Luckily, theres a great solution for this. In Android, you can use something called "plurals".
You can use plurals in their own resource file, or just add them to the
strings.xml file. I like to have them in my
strings.xml file, so I can keep track of all strings in one place, and easily translate them to other locales.
strings.xml, add a
plurals element, like below:
<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="numberOfDeletedItems"> <item quantity="one">Deleted %d message</item> <item quantity="other">Deleted %d messages</item> </plurals> <!-- other strings... --> </resources>
You can then add the same element to your other
strings.xml files, to get them translated.
To use the plural string in your app, you get it like this:
int deletedItemCount = doSomeAction(); String formattedText = getResources() .getQuantityString(R.plurals.numberOfDeletedItems, deletedItemCount, deletedItemCount);
Depending on the
deletedItemCount variable, you will now get a formatted string, with the correct pluralization.
There are several different values for
quantity, for more information, and tips check out the documentation.