首页 > 解决方案 > 更改语言环境在 Android 10 中停止工作

问题描述

我一直在使用下面的代码来更改 Android 应用程序中的语言环境(该应用程序有自己的语言环境设置,可能与操作系统语言环境不同)。该代码在 Android 9 (P) 之前运行良好。在 Android 10 (Q) 中,它停止工作,资源没有更新。我在 Android 10 发行说明中看不到任何与语言环境相关的更改。什么可以在 Android 10 中破坏此代码?如果它是已知的,有人可以指出我的解决方案吗?

private fun setLocale(context: Context, language: String): Context {
    //...persist here. persisting works fine
    return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        updateResources(context, language)
    else
        updateResourcesLegacy(context, language)
}

@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)

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

    return context.createConfigurationContext(configuration)
}

更新

我发现此代码在升级到较新版本的androidx.appcompat:appcompat. 我可以缩小范围:它适用1.2.0-alpha011.2.0-alpha02.

我在发行说明中看到1.2.0-alpha02与上下文相关的 3 个更改:https ://developer.android.com/jetpack/androidx/releases/appcompat#1.2.0-alpha02

标签: androidandroid-architecture-componentsandroid-jetpackandroid-10.0

解决方案


我正在发布对我有用的 Google 员工的回复。我在他们的问题跟踪器上问了这个问题,他们建议创建一个新的配置实例而不是修改现有的实例。

所以,而不是这个(下面不起作用):

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

它应该是(这有效):

val configuration = Configuration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)

这种方式在他们的测试中使用:


推荐阅读