Saturday 11 January 2014

Formatted strings and plurals

If you have been programming in Android for a while, you probably know that string resources should be put in a centralized file, strings.xml in the res/values directory.
This way you can easily change string resources by changing the corresponding value in the strings.xml file (even people who can't program in Android would be able to do this). You can also create different strings.xml files for different languages in order to internationalize your app.

But probably not everyone knows that you can do more than this. Let's see what...


1) FORMATTED STRINGS

You can of course format strings in the strings.xml file. The syntax is the same as that of the java.util.Formatter class (see for more details).
Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="login_message">Login %s!</string>
...
</resources>

and here is how you can use this string with a paramter:

getString(R.string.login_message, name)

2) PLURALS

With plurals you can obtain different strings depending on the amount of input. Here is a complete example of what you can do:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="score_count">
    <item quantity="zero">Your score is zero! Very bad!</item>
    <item quantity="one">Your score is one! This is not very good!</item>
    <item quantity="two">Your score is two! Come on!</item>
    <item quantity="few">Your score is %d!</item>
    <item quantity="many">Your score %1$d! %2$s, well done!</item>
    <item quantity="other">Your score is %1$d!! %2$s, try again!</item>
</plurals>
...
</resources>

and here is how you can use this plurals resource with paramters: the system will select the correct string (using and formatting the parameters if necessary) depending on the amount of input:

getQuantityString(R.plurals.score_count, score, score, yourname);

As you can see, the secondo paramter (score) is used to determine which string has to be chosen (it is the amount), while the other two parameters (score and yourname) are used for formatting the chosen string.

1 comment:

  1. Hello! I suggest to try POEditor which is an online translation management platform created to simplify the workflow and make things easier with localization.

    ReplyDelete