Android 13以下版本应用上下文为何无法适配单应用语言?
解决Android 12应用上下文适配单应用语言的问题
核心原因
Android 12及以下版本中,Application 上下文的资源配置不会自动跟随AppCompatDelegate设置的应用 locales,只有Activity上下文会通过AppCompat框架自动完成配置同步。
具体修复步骤
重写Application的attachBaseContext方法,手动将AppCompatDelegate的 locales 配置同步到应用上下文:
@Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // 获取当前AppCompatDelegate设置的locales LocaleListCompat appLocales = AppCompatDelegate.getApplicationLocales(); if (!appLocales.isEmpty()) { // 创建适配后的上下文 Context updatedContext = ContextCompat.createConfigurationContext(base, appLocales.toConfiguration()); // 更新应用上下文的资源配置 getResources().updateConfiguration(updatedContext.getResources().getConfiguration(), updatedContext.getResources().getDisplayMetrics()); } }切换语言后主动更新应用上下文配置
调用AppCompatDelegate.setApplicationLocales()完成语言切换后,除了重启Activity,还需要同步更新Application的上下文配置:// 设置新的目标语言 AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("zh-CN")); // 获取应用上下文实例 Context appContext = getApplicationContext(); // 基于最新locales生成配置 Configuration newConfig = AppCompatDelegate.getApplicationLocales().toConfiguration(); // 更新应用上下文的资源配置 appContext.getResources().updateConfiguration(newConfig, appContext.getResources().getDisplayMetrics());清理资源缓存
如果应用中存在全局的资源缓存(比如提前初始化的字符串常量),需要在语言切换后清空缓存,确保后续使用应用上下文获取的是新语言的资源。
注意事项
- 不要直接替换Application的baseContext,通过
updateConfiguration更新资源配置可避免上下文不一致的问题。 - Android 13+系统已原生支持应用级 locales 同步到Application上下文,无需额外处理。
内容的提问来源于stack exchange,提问作者Linus Hägerbrand
相关产品推荐
相关产品推荐

