Mohd Ikram
Mohd Ikram

Reputation: 101

Manage Locale in Android Jetpack Compose

How do I manage the locale with android Jetpack Compose. How do compose find the locale to set in the view.

Upvotes: 10

Views: 8730

Answers (3)

Ben.Slama.Jihed
Ben.Slama.Jihed

Reputation: 534

import androidx.compose.ui.text.intl.Locale
val local =  Locale.current

java.util.Locale(locale.language)

Upvotes: 0

Stephen Vinouze
Stephen Vinouze

Reputation: 2065

To access the Locale from a Composable, use this:

Locale.current

https://developer.android.com/reference/kotlin/androidx/compose/ui/text/intl/Locale#current()

Upvotes: 5

Stylianos Gakis
Stylianos Gakis

Reputation: 1023

androidx.compose.ui.text.intl.Locale exists, and if it fulfills your needs that is great, you can use Locale.current however very often you want a java.util.Locale instead.

To do that, I suggest a function like this

@Composable
@ReadOnlyComposable
fun getLocale(): Locale? {
  val configuration = LocalConfiguration.current
  return ConfigurationCompat.getLocales(configuration).get(0)
}

Or if you want do default to whatever Locale.getDefault() returns and not null, you can adjust it to this:

@Composable
@ReadOnlyComposable
fun getLocale(): Locale {
  val configuration = LocalConfiguration.current
  return ConfigurationCompat.getLocales(configuration).get(0) ?: LocaleListCompat.getDefault()[0]!!
}

It's important to use LocalConfiguration.current so that if there is a configuration change, the function will recompose and you will get the latest Locale instead of a stale one. I've recently had this discussion where this was mentioned.

ConfigurationCompat.getLocales makes sure that it works on all API versions. If you are on API >= 24 anyway, go ahead and use LocalConfiguration.current.locales directly.

Bonus: This also works perfectly when using the per-app language APIs, since it returns whatever language was chosen in the app language settings.

Upvotes: 13

Related Questions