如何在Android数量字符串(复数)中使用零数量大小写?



我试图在我的Kotlin应用程序中使用Resources中的getQuantityString方法来检索基于android开发人员指南Quantity StringQuantity StringsOneother的情况是可以的,但zero不工作。这是我的代码。

// text
txtNewProfileCount.text = resources.getQuantityString(
            R.plurals.shortlists_profile_count,
            filteredCandidateVMList.size,
            filteredCandidateVMList.size
        )
// plurals code
<plurals name="shortlists_profile_count">
    <item quantity="zero">Sorry, there are no new profiles in your various shortlists</item>
    <item quantity="one">Please review the new profile in your various shortlists</item>
    <item quantity="other">Please review the %1$d new profiles in your various shortlists</item>
</plurals>

如果数量是oneother,结果是正确的。但是在zero的情况下,结果是 Please review the 0 new profiles in your various shortlists .这不是我想要的结果。当数量为zero时如何解决?

英文中从不使用zero大小写。英语只使用oneother。复数资源仅用于特定语言的语法惟一结构。这在文档中有解释:

要使用的字符串的选择完全基于语法必要性。在英语中,表示0的字符串甚至会被忽略如果数量是0,因为0和2在语法上没有区别,或除1以外的任何数字("零本书"、"一本书"、"两本书"),等等)。

所以你必须在你的代码中使用if语句手动选择一个单独的String资源。

Android Plurals现在不支持零大小写。因此,您需要为此创建自己的函数。

下面是一个例子。

fun getQuantityString(resources:Resources, resId:Int, quantity:Int, zeroResId:Int):String {
  if (quantity == 0) {
    return resources.getString(zeroResId)
  } else {
    return resources.getQuantityString(resId, quantity, quantity)
  }
}

最新更新