Plurals in android

Updated 18 December 2016


While creating an android application with all that strings and data sometimes the strings are based on the data we are getting. One of the best example, and most important one too, is showing Singulars and Plurals in application. Fore example if I am having 1 mango then the string should be like

But if I have 10 then?

Then I have to add a condition in my code and declare another key with an integer place holder like

Looks like a problem, right? But no, android has a solution for it which most of us don’t know its “Quantity Strings” or you can say “Plurals”. In plurals you can give more than one statement to a resource based on the number of items (in our case mangoes) you got. In-spite of only numbers there are many other words supported such as few, many, other etc.

Also one of the advantage of using plurals is when you have more than one language support in your application. Different languages have different way of representing singulars and plurals and also distinctive ways of differentiating.  Plurals also helps you in that case for-example in English you will mention

But in Indonesian there is no difference in string based on number, so it will be like

How to add it in Code:

Now you have declared your plurals in xml file, its turn for calling them in your code where you are getting the quantity based on which the correct string will be chosen. For calling plurals you can’t use getString(), you have to use method getQuantityString() like

The first number_of_items is for the selection of the correct string only and as we have applied an integer placeholder, for that we had again passed number_of_items. If we are not using any string placeholders then we have to pass only two parameters to the method. So now we can use different strings based on different number in different languages. isn’t it interesting?


. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home