Android plurals treatment of “zero”

前端 未结 6 1456
悲哀的现实
悲哀的现实 2020-12-04 08:38

If have the following plural ressource in my strings.xml:

   
        No item
           


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 09:01

    I've wrote a Kotlin extension to handle all the scenarios that I can think about.

    I have zeroResId as optional, so that sometimes we want to handle the zero by displaying "No Items", rather than "0 Items".

    English treats zero grammatically as plural.

    The selection of which string to use is made solely based on grammatical necessity.

    In English, a string for zero is ignored even if the quantity is 0, because 0 isn't grammatically different from 2, or any other number except 1 ("zero books", "one book", "two books", and so on).

    https://developer.android.com/guide/topics/resources/string-resource.html#Plurals

    fun Context.getQuantityStringZero(
        quantity: Int, 
        pluralResId: Int, 
        zeroResId: Int? = null
    ): String {
        return if (zeroResId != null && quantity == 0) {
            resources.getString(zeroResId)
        } else {
            resources.getQuantityString(pluralResId, quantity, quantity)
        }
    }
    

提交回复
热议问题