18

在 Android 字符串中,您可以定义复数来处理翻译,具体取决于提供给字符串的实际数字,如此处所述。字符串还允许指定多个位置参数,类似于sprintf在许多语言中所做的。

但是,请考虑以下字符串:

<resources>
    <string name="remaining">%1$d hours and %2$d minutes remaining.</string>
</resources>

它包含两个数字,我如何将其转换为 Android 中的复数?所有示例始终仅使用单个参数。这甚至可能吗?

4

3 回答 3

7

上一个答案使用字符串连接,从 i18n 的角度来看这是不正确的。对于原始字符串“剩余 %1$d 小时和 %2$d 分钟”。使用字符串连接会强制将“剩余”翻译到结尾,这可能不适合某些语言。

我的解决方案是:

<resources>
     <string name="remaining">Time remaining: Hours:%1$d Minutes:%2$d.</string>
</resources>

或者也许以“剩余时间”为标题。

http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling中提到了这个解决方案

通常可以通过使用数量中性的公式来避免数量字符串,例如“书籍:1”

于 2016-05-04T15:49:57.350 回答
5

getQuantityString有一个重载版本,它接受一个字符串 id、数量和varargs对象,您可以使用它们来格式化您的字符串。尽管似乎可以使用复数,但对我来说这听起来很奇怪。您可以使用DateUtil中包含的辅助方法,这些方法已经本地化并处理单数/复数,然后使用这些辅助方法的结果完成您的字符串。例如getRelativeTimeSpanString

<plurals name="number_of_emails">
    <item quantity="one">%d email</item>
    <item quantity="other">%d emails</item>
</plurals>

<plurals name="number_of_messages">
    <item quantity="one">%d message</item>
    <item quantity="other">%d messages</item>
</plurals>

然后你可以用它getQuantityString来检索这两个部分并将其合并为一个。

于 2015-12-21T10:26:35.170 回答
2

字符串.xml

<plurals name="lbl_items_selected">
    <item quantity="one">%d item out of %d items Selected</item>
    <item quantity="other">%d items out of %d items Selected</item>
</plurals>

科特林文件

resources.getQuantityString(
    R.plurals.lbl_items_selected, //plural from strings.xml file
    size, //quantity 
    size, //var arg - first parameter
    allItemCount //var arg - second parameter
)

这将返回:

如果 size = 1:选择 10(allItemCount) 个项目中的 1 个项目

如果 size = 2(或更多):选择 10(allItemCount)个项目中的 2(给定大小)项目

于 2019-09-23T11:12:38.790 回答