Rango527
Rango527

Reputation: 221

How to use zero quantity case in Android quantity strings (plurals)?

I am trying to use the getQuantityString method in Resources to retrieve Quantity Strings based on android developer guidelines Quantity String in my Kotlin application. One and the other case is ok, but zero is not working. This is my code.

// 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>

In case the quantity is one and other, the result is correct. But in the zero cases, the result is Please review the 0 new profiles in your various shortlists. This isn't the result I want. How to solve when the quantity is zero?

Upvotes: 1

Views: 893

Answers (2)

Daniel.Wang
Daniel.Wang

Reputation: 2496

Android Plurals is not support zero case now. So you need to make your own function for this.

Here is one example.

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)
  }
}

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93902

The zero case is never used in English. English uses only one and other. Plural resources are intended only for grammatically unique constructs of specific languages. This is explained in the documentation:

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

So you have to manually select a separate String resource using an if statement in your code.

Upvotes: 5

Related Questions