Android Pluralization not working, need help

老子叫甜甜 提交于 2019-12-03 07:16:30

It appears that you need to specify the count twice, the first is used to determine the string to use, and the second is the one that is replaced into the string. e.g.

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

And at least in my testing so far, the xliff:g elements in the resource aren't needed.

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);

Same problem here! I guess it is just a flaw in the documentation. The "pure" getQuantitiyString(int, int) method does just get a text resource, without any formatting. As superfell stated: just use the getQuantityString(int, int, Object...) method and hand over your integer value twice.

I'd hoped this worked the same way you did, but it simply doesn't!!

PS: maybe check an answer as the correct one? ;-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!