android - 更改语言环境在 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-alpha01
于1.2.0-alpha02
.
我在发行说明中看到1.2.0-alpha02
与上下文相关的 3 个更改:https ://developer.android.com/jetpack/androidx/releases/appcompat#1.2.0-alpha02
- 确保基本上下文始终是包装器 (aosp/1194355)
- 添加了一些改进,以便在修改基本上下文配置时更加聪明 (aosp/1204543)
- 为 Robolectric 禁用 createConfigurationContext() (aosp/1186218)
解决方案
我正在发布对我有用的 Google 员工的回复。我在他们的问题跟踪器上问了这个问题,他们建议创建一个新的配置实例而不是修改现有的实例。
所以,而不是这个(下面不起作用):
val configuration = context.resources.configuration
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
它应该是(这有效):
val configuration = Configuration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
推荐阅读
- python - 将年份添加到当前日期
- sql - 在 SQL 中 - 有没有办法按 ID 组合或分组而不按 case 语句分组
- php - PHP循环遍历数组以获取特定值
- sql - 基于尚未匹配的第一个匹配的出现顺序的 SQL 连接
- c++ - 什么是 char (*var)[6] 和 char* var[6]?
- android - Flutter 无法从资产文件夹中检测到“model.tflite”文件(FileNotFoundException)
- database - Kubernetes 上的 etcd 数据库集群行为不端
- c# - 有没有办法重定向到新页面是 System.NullReferenceException 被触发?
- php - 将额外模型附加到 BelongstoMany 关系
- javascript - javascript d3 timeParse utcParse