3

I was wondering if there is any easy way to format an integer based on negative, zero and positive using the plural resources mechanism in android?

My desired answer would be

  • if getRemaining() < -1 then "|getRemaining()| days ago"
  • if getRemaining() == -1 then "|getRemaining()| day ago"
  • if getRemaining() == 0 then "getRemaining() days remaining"
  • if getRemaining() == 1 then "getRemaining() day remaining"
  • if getRemaining() > 1 then "getRemaining() days remaining"

Right now I achieve this by following code

if (item.getRemaining() > -1) {
        holder.remainingTV.setText(res.getQuantityString(R.plurals.plural_remaining, item.getRemaining(),
            item.getRemaining()));
} else {
        holder.remainingTV.setText(res.getQuantityString(R.plurals.plural_ago, -item.getRemaining(), -item.getRemaining()));
}

My resources looks like this

<plurals name="plural_remaining">
    <item quantity="one">%d Day Remaining</item>
    <item quantity="other">%d Days Remaining</item>
</plurals>

<plurals name="plural_ago">
    <item quantity="one">%d Day Ago</item>
    <item quantity="other">%d Days Ago</item>
</plurals>

How can I achieve the aforementioned solution without having to split them based on -ve and +ve number in android?

Samuel Robert
  • 10,106
  • 7
  • 39
  • 60

1 Answers1

0

You can use the absolute value of the quantity into the getQuantityString like this (in Kotlin) or Math.abs (in Java) :

getQuantityString(
   R.plurals.a_plural,
   quantityValue.absoluteValue,
   quantityValue
)

Its will handle : -1, 0, 1 and the others values