0

我的应用程序中有一个功能,用户可以从应用程序内部更改语言。该代码在 Android 11 之前运行良好。但从 Android 12 开始,我无法以编程方式更改语言。但是当操作系统的语言发生变化时,应用程序语言也会发生变化。

Android 12 是否已弃用语言环境或任何其他支持?

任何帮助深表感谢。提前致谢。

 // 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
}
4

1 回答 1

0

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)
}
于 2022-02-21T19:40:34.600 回答