【问题标题】:Plural definition is ignored for zero quantity零数量忽略复数定义
【发布时间】:2013-06-20 02:56:27
【问题描述】:

我使用plurals 为Android 应用程序编译一个数量字符串。我完全按照教程中可以找到的内容进行操作:

res.getQuantityString(
    R.plurals.number_of_comments, commentsCount, commentsCount);

这里是复数的定义:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="number_of_comments">
        <item quantity="zero">No comments</item>
        <item quantity="one">One comment</item>
        <item quantity="other">%d comments</item>
    </plurals>
</resources>

有趣的是,输出字符串与我定义的很奇怪:

commentsCount = 0 => "0 comments"  
commentsCount = 1 => "One comment"  
commentsCount = 2 => "2 comments"

我猜这是因为文档将When the language requires special treatment of the number 0 (as in Arabic). 声明为zero 数量。有什么方法可以强制我的定义?

【问题讨论】:

    标签: android android-xml android-resources plural


    【解决方案1】:

    在 Kotlin 中(感谢 Dalmas):

    val result = commentsCount.takeIf { it != 0 }?.let {
        resources.getQuantityString(R.plurals.number_of_comments, it, it)
    } ?: resources.getString(R.string.number_of_comments_zero)
    

    【讨论】:

      【解决方案2】:

      复数是 Unicode 形式。所有复数值here。 在英语中,零的复数形式如 2, 3,4 所以你必须 if else this value 才能使用其他字符串。

      【讨论】:

        【解决方案3】:

        根据the documentation:

        选择使用哪个字符串完全基于 语法必要性。在英语中,零的字符串将被忽略 即使数量为 0,因为 0 在语法上没有区别 从 2 或除 1 以外的任何其他数字(“零书”、“一本书”、“二 书”等)。

        如果你还想使用自定义字符串为零,你可以在数量为零时加载不同的字符串:

        if (commentsCount == 0)
            str = res.getString(R.string.number_of_comments_zero);
        else
            str = res.getQuantityString(R.plurals.number_of_comments, commentsCount, commentsCount);
        

        【讨论】:

        • 蹩脚的 android 让我们做这些肮脏的变通办法。 plurals 定义应该在所有情况下都使用,这样我们的代码就更干净了!
        • 那么,为什么 android 将自动完成功能设置为 zero、few、many 等,如果它们无论如何都不起作用?
        • @htafoya 他们做工作,他们只是没有被映射为英语,因为没有语法上的必要性。数量和语言的组合决定了类别(零、一、二、少数、许多、其他),对于“en”,它只是one 或other。对于威尔士语,共有六个类别。由翻译人员决定他们的语言在哪种情况下使用了哪些类别。
        • @LWChris 好的,我的问题是默认语言(没有 mods 的 res 文件夹)不是英文的,android 认为它是这样,它忽略了零文本?有没有办法设置默认语言属性?
        • 无论如何,他们应该用英语启用它,因为很多时候你使用句子而不是单个单词。而且我更愿意放置“无”或“空”而不是 0。
        猜你喜欢
        • 2020-05-19
        • 1970-01-01
        • 2014-04-23
        • 2011-12-13
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        • 2021-04-29
        • 1970-01-01
        相关资源
        最近更新 更多