5

我想在我的 Android 项目中使用复数。但是,我提供的值可以是浮点值。

因此,例如,在设置 1.5 星时,我想让这明白,它不是 1 星,而是 1.5星

<plurals name="stars">
  <item quantity="one">%d star</item>
  <item quantity="other">%d stars</item>
</plurals>

但是,Android 系统似乎只使用整数值 (%d)。

该方法如下所示:

String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)

其中数量定义为Int

有什么解决办法吗?

4

2 回答 2

2

经过进一步研究,似乎没有很好的解决方案

正如在其他答案中所看到的,它们总是需要大量的“手动处理”,而不需要与创建单独的字符串资源不同的工作流程。

一般建议似乎是手动舍入/处理浮点值(例如检查浮点值是否匹配 1.0),然后为复数调用使用适当的 Int 值。

但是除了没有真正使用复数之外,这还伴随着其他语言的问题(例如,我不知道 1.5 星在另一种语言中是否也会像英语一样是复数),因此这些舍入选项可能并不普遍适用。

所以答案是:似乎没有完美的解决方案(意思是由Android系统“自动”解决)。

因此,我实际上做的是简单地选择异常并在那里使用不同的字符串。所以目前的(伪代码)方式看起来像

// optionally wrap different languages around
// if language == English

   when (amountStars) {
    is 1.0 -> getString(R.string.stars_singular, 1) 
    ... ->
    else -> getString(R.string.stars_plural, amountStars)
   }
// if language == Chinese ...

其他情况必须“硬编码”。因此,例如,您必须决定 0 是否意味着

"0 stars" (plural string) or

"no star" (singular string)

But there seems no real benefit of using plurals over separate string resources with common placeholders. On the other hand this (at last for me) gives more flexibility for formatting options. For example, one may create a text like "1 star and a half" where it becomes singular again (even though numerically we would write 1.5 stars).

于 2019-03-05T15:52:03.917 回答
0

只需这样做:

getQuantityString(R.plurals.stars, quantity > 1f ? 2 : 1, quantity):

并将字符串中的 %d 替换为 %f。

于 2019-02-26T16:54:54.603 回答