Android 具有多个参数的复数字符串

Android Plural Strings with multiple Parameters

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

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

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

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

getQuantityString has an overloaded version that takes a String id, the quantity and a varargs of object that you could use to format your string. Even though seems possible to use plural, it sounds strange to me for time. You could use the helper methods contained in DateUtil, which are already localized and take care of singular/plural and then complete your string with the results of these helper methods. E.g. 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把两部分取出来合二为一了。

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

我的解决方案是:

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

或者用 "Time remaining" 作为标题。

http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

中提到了此解决方案

It's often possible to avoid quantity strings by using quantity-neutral formulations such as "Books: 1"

strings.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>

Kotlin 文件

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

这将 return :

if size = 1:已选择 10(allItemCount) 项中的 1 项

if size = 2(或更多):从 10(allItemCount) 件商品中选择了 2(给定尺寸)件商品