Android Pluralization not working, need help

Viewed 6317

I've been attempting to utilize the plurals resource with Android but have not had any luck.

Here is my resource file for my plurals:

<?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
        <plurals name="meters">
            <item quantity="one">1 meter</item>
            <item quantity="other">
                <xliff:g id="count">%d</xliff:g>
                meters
            </item>
        </plurals>
        <plurals name="degrees">
            <item quantity="one">1 degree</item>
            <item quantity="other">
                <xliff:g id="count">%d</xliff:g>
                degrees
            </item>
        </plurals>
    </resources>

...and then here is the code I am using when I attempt to extract the quantity string from my resources:

Resources res = this.getResources();
tTemp.setText(res.getQuantityString(R.plurals.degrees, this.mObject.temp_c.intValue()));

...but the text in the TextView remains to be %d degrees and %d meters.

Does anyone know what is happening? I've debugged the code and the res.getQuantityString(...) call is returning a String whose value is %d degrees or %d meters. Though when the quantity happens to be 1 it does correctly evalute to 1 degree or 1 meter.

Thanks in advance for any help!

Regards, celestialorb.

3 Answers

Android "supports" the use of plurals by use of R.plurals which is practically undocumented. Diving into the source code reveals that you should be able to have the following possible versions of a string:

  • "zero"
  • "one"
  • "few" (for exactly 2)
  • "other" (for 3 and above)

However, I've found that only "one" and "other" actually work (despite the others being used in the android source!).

To use plurals you want to declare you pluralizable strings in a similar way to normal string resources:

<resources>
  <plurals name="match">
    <!-- Case of one match -->
    <item quantity="one">1 match</item>
    <!-- Case of several matches -->
    <item quantity="other">%d matches</item>
  </plurals>
</resources>

Then to actually use them in code, use code similar to what superfell suggested above:

String text = getResources().getQuantityString(R.plurals.match, myIntValue, myIntValue);
myTextView.setText(text);
Related