What is the right way to use Android Plurals?

111 Views Asked by At

I have method that gets a list (listOf(1, 5, 10, 15, 30)) and TimeType (MINUTES or HOURS) as parameters. And I have to use plurals for MINUTES so that if I choose 1 I get "minute" and if I choose 5 or 10 I get "minutes". But I have problems with that. Could you please help me?

val title = when(type){
            TimeType.MINUTES -> R.string.time_minutes
            TimeType.HOURS -> R.string.time_hours
        }

title = String.format(getString(title), interval)
    <plurals name="amountOfMinutes">
        <item quantity="one">@string/minute</item>
        <item quantity="other">@string/minutes</item>
    </plurals>

Upd.

I tried to use it like that but the problem is that val title should be int but in my case it becomes Any and getString in format dosn't accept it.

val title = when(type){
            TimeType.MINUTES -> for (i in intervals){
                resources.getQuantityString(R.plurals.amountOfMinutes, i, i)
            }
            TimeType.HOURS -> R.string.options_for_reminder_time_hours
        }
1

There are 1 best solutions below

1
On

You shouldn't be using a string resource like that in it, for two reasons. First off, it just confuses things. Secondly, by telling the translator that these are plurals of each other they have more context to translate. It should be

<plurals name="amountOfMinutes">
        <item quantity="one">%d minute</item>
        <item quantity="other">%d minutes</item>
</plurals>

Notice we also put the quantity in the string, to get with getQuantityString. This is because putting it first like that isn't always right. Some languages say "minute one" instead of one minute. Some use characters other than spaces to separate them. Let the translators do as much of that as possible, you're assuming too much about how English works.