Plurals does not work as intended in android

I use multiple lines provided by android-sdk. I used the following code to create a multiple line:

<plurals name="valuestr"> <item quantity="zero">Choose a value.</item> <item quantity="one">%d unit.</item> <item quantity="other">%d units.</item> </plurals> 

Java Code:

 textView.setText(getResources().getQuantityString(R.plurals.valuestr,0,0)); 

When I set any value other than '0', it works fine, but when I set '0', it shows '0 unit.' .

Please, help!

Update

When searching on the Internet, I came across a workaround that uses the java.text.MessageFormat class:

 <resources> <string name="item_shop">{0,choice,0#No items|1#One item|1&lt;{0} items}</string> </resources> 

Then from the code, all you need to do is the following:

 String fmt = resources.getText(R.string.item_shop); textView.setText(MessageFormat.format(fmt, amount)); 

Read more about format strings in javadocs for MessageFormat

+6
source share
2 answers

A G + post about this has recently been posted. In short, this is because he will not select the nearest Integer match (0 = zero), but because he will look for the best grammar choice.

Your example uses units. Proper use will be; 0 units 1 unit 2 units

Creation, zero equal to almost any other value above 1

Read the whole story here; https://plus.google.com/116539451797396019960/posts/VYcxa1jUGNo

+8
source

The plurals defined in the <plurals> sections of the resource files should be used only for grammatical differences with respect to singular / multiple lines. You should not use them for other display logic, just like you. Instead, you should add validation logic to your code.

The Android Developer Guide clearly states the following:

Although historically called the "row count" (and is still referred to in the API), the row count should only be used for plurals. It would be a mistake to use the number of lines to implement something like Gmail. β€œInbox” and β€œInbox (12)” when there are unread messages, for example. It may seem convenient to use numeric strings instead of the if statement, but it is important to note that some languages ​​(such as Chinese) do not make these grammatical differences at all, so you will always get a different string.

Your solution - although technically working for your current implementation - does not seem like a clean solution, in my opinion. Future business requirements may require the inclusion of more complex logic than simply displaying other text. Or you can have a common line "no items selected" in the resource file used in different places, which can be reused only if you do not stick to your decision.

Generally, I would avoid using two different formatting methods (formatting the String.format %d style compared to TextFormat {0} formatting and choosing the one that you stick with throughout your application.

0
source

All Articles