CODAR747
CODAR747

Reputation: 174

How can I programmatically set the language in Jetpack Compose without AppCompatDelegate?

I'm trying to implement language selection functionality in my Jetpack Compose app. However, I encountered a roadblock when attempting to use AppCompactDelegate to achieve this. It seems that AppCompactDelegate is not available in Jetpack Compose.

Here's the code snippet I tried:

fun languageUpdate(context: Context, language: String){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU){
            context.getSystemService(LocaleManager::class.java)
                .applicationLocales = LocaleList.forLanguageTags(language)
        } else {
            AppCompactDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(language))
        }
    }

Since AppCompactDelegate isn't an option in Jetpack Compose, I'm seeking alternative solutions to programmatically set the language in my app. Any guidance or suggestions would be greatly appreciated.

Upvotes: 0

Views: 1514

Answers (2)

mmmatey
mmmatey

Reputation: 684

You can combine what Megh Lath proposed, but with a combination of using context.createConfigurationContext for android 12 and above, because resources.updateConfiguration was deprecated for android 12 and on.

val context = LocalContext.current
val resources = context.resources
val configuration = resources.configuration

val newContext = context.createConfigurationContext(configuration.apply {
    setLocale(newLocale)
})
LocalContext.current = newContext

If you want to call AppCompatDelegate.setApplicationLocales(), you can do it in SideEffect block or LaunchedEffect in Jetpack Compose UI, depending on your needs:

SideEffect {   
    AppCompatDelegate.setApplicationLocales()
}

Upvotes: 0

Megh Lath
Megh Lath

Reputation: 2138

You can directly update the application's configuration using Resources.updateConfiguration() method.

Here's how you can implement it:


fun updateLanguage(context: Context, language: String) {
    val locale = Locale(language)
    Locale.setDefault(locale)

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

    context.resources.updateConfiguration(configuration, context.resources.displayMetrics)
}

And call it through onCreate() or if you want to call it from composable function then cast context as Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    updateLanguage(this, "es")
}

or,

@Composable
fun Sample() {
    val context = LocalContext.current as Activity
    updateLanguage(this, "es")
}

Upvotes: 0

Related Questions