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
1 |
<string name="mango">I have a mango.</string> |
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
1 |
<string name="mangoes">I have 10 mangoes.</string> |
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
1 2 3 4 |
<plurals name="items_found"> <item quantity="one">Total %1$d item found.</item> <item quantity="other">Total %1$d items found.</item> </plurals> |
But in Indonesian there is no difference in string based on number, so it will be like
1 2 3 |
<plurals name="items_found"> <item quantity="other">Total %1$d item yang ditemukan.</item> </plurals> |
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
1 |
textview.setText(getResources().getQuantityString(R.plurals.items_found, number_of_items, number_of_items)); |
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?
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.