Home > Software design >  How to apply Locale to Plural resource?
How to apply Locale to Plural resource?

Time:06-30

I'm using plurals in resources just like docs saying:

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

My app using only one language, so i want to use my language's rules no matter which language is set on device. How can i use Locale in my plurals?

<plurals name="amount_of_hours">
        <item quantity="zero">%d zero</item>
        <item quantity="one">%d one</item>
        <item quantity="two">%d two</item>
        <item quantity="few">%d few</item>
        <item quantity="many">%d many</item>
        <item quantity="other">%d other</item>
    </plurals>

// set Locale to this plural 
context.resources.getQuantityString(R.plurals.amount_of_hours, hours, hours)

CodePudding user response:

You can create a Configuration with a different locale as described in https://stackoverflow.com/a/42269965/2921519 and call getQuantityString on it:

val configuration = Configuration(context.resources.configuration)
configuration.setLocale(locale)

// For N or above only. See linked answer for backwards compatibility.
val localeContext = context.createConfigurationContext(config)
localeContext.resources.getQuantityString(...)
  • Related