Aman Masipeddi
Aman Masipeddi

Reputation: 11

Changing Locale/Language of the app in Android 12

I have a feature in my app where user can change the language from inside the app. The code was working fine till Android 11. But from Android 12, I am not able to change the language programmatically. But the app language is being changed when the language of the OS is changed.

Is the Locale or any other support is deprecated for Android 12?

Any help is much appreciated. Thanks in Advance.

 // Below code is used to override configuration when the locale is changed.
override fun attachBaseContext(base: Context) {
    super.attachBaseContext(updateBaseContextLocale(base))
}

open fun updateBaseContextLocale(context: Context): Context? {
    val languageCode: String
    languageCode = "de"
    val locale = Locale(languageCode)
    Locale.setDefault(locale)
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        updateResourcesLocale(context, locale)
    } else updateResourcesLocaleLegacy(context, locale)
}

@TargetApi(Build.VERSION_CODES.N)
open fun updateResourcesLocale(context: Context, locale: Locale): Context? {
    val configuration: Configuration = context.resources.configuration
    configuration.setLocale(locale)
    return context.createConfigurationContext(configuration)
}

open fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context? {
    val resources: Resources = context.resources
    val configuration: Configuration = resources.getConfiguration()
    configuration.locale = locale
    resources.updateConfiguration(configuration, resources.getDisplayMetrics())
    return context
}

Upvotes: 1

Views: 2855

Answers (1)

Omar Zerir
Omar Zerir

Reputation: 41

I have faced the same problem on Android-12, I just fixed it by implement attachBaseContext method on the activity..

override fun attachBaseContext(newBase: Context) {
    /**
     * handle locale
     */
    val currentLang = "en" // to get from sharedPref or whatever
    newBase.resources.configuration.setLocale(Locale(currentLang))

    applyOverrideConfiguration(newBase.resources.configuration)
    super.attachBaseContext(newBase)
}

Upvotes: 4

Related Questions