在 android 中通过代码动态切换应用语言时,仅修改当前 activity 的 configuration 并调用 recreate() 不足以更新已加载的 fragment 或其他 activity,需在所有 activity 生命周期关键节点(如 attachbasecontext)统一处理语言配置。
在 android 中通过代码动态切换应用语言时,仅修改当前 activity 的 configuration 并调用 recreate() 不足以更新已加载的 fragment 或其他 activity,需在所有 activity 生命周期关键节点(如 attachbasecontext)统一处理语言配置。
在 Android 8.0(API 26)之后,尤其是 targetSdkVersion ≥ 31 的项目中,Configuration.setLocale() 已被弃用,且 resources.updateConfiguration() 不再影响新创建的 Context(如 Fragment、Dialog、Adapter 等),导致你遇到的现象:主 Activity 和首次加载的 Fragment 切换成功,但后续 replace 进来的 Fragment 仍显示旧语言——这是因为 Fragment 使用的是其宿主 Activity 重建前的 Context,或自身持有的资源未刷新。
✅ 正确做法:在 Activity 创建前(attachBaseContext)注入自定义 Locale,并确保所有 Context(包括 Fragment)均继承该配置。
✅ 推荐实现步骤(适配 API 21+,兼容 targetSdkVersion 31+)
1. 创建语言管理工具类
public class LanguageUtils {
private static final String PREF_LANG = "pref_language";
private static final String DEFAULT_LANG = "en";
public static void setAppLanguage(@NonNull Context context, @NonNull String languageCode) {
SharedPreferences prefs = context.getSharedPreferences("config", Context.MODE_PRIVATE);
prefs.edit().putString(PREF_LANG, languageCode).apply();
// 立即刷新当前进程的资源配置(需配合 attachBaseContext 使用)
updateResources(context, languageCode);
}
public static String getAppLanguage(@NonNull Context context) {
SharedPreferences prefs = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return prefs.getString(PREF_LANG, DEFAULT_LANG);
}
private static void updateResources(@NonNull Context context, @NonNull String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration config = resources.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(locale);
} else {
config.locale = locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.createConfigurationContext(config); // 仅用于触发资源重载逻辑,不直接使用返回值
}
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
}
2. 创建 BaseActivity(所有 Activity 继承它)
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context newBase) {
String lang = LanguageUtils.getAppLanguage(newBase);
Context context = updateBaseContextLocale(newBase, lang);
super.attachBaseContext(context);
}
private Context updateBaseContextLocale(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, locale);
} else {
return updateResourcesLegacy(context, locale);
}
}
@SuppressWarnings("deprecation")
private Context updateResourcesLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
@TargetApi(Build.VERSION_CODES.N)
private Context updateResources(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
}
3. 所有 Activity 改为继承 BaseActivity
public class MainActivity extends BaseActivity {
// 无需在 onCreate/recreate 中手动 updateConfiguration!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 切换语言示例(如点击按钮)
private void onLanguageToggle(String langCode) {
LanguageUtils.setAppLanguage(this, langCode);
recreate(); // 触发 attachBaseContext → 新 Context + 资源重建
}
}
4. Fragment 语言自动同步(无需额外处理)
只要 Fragment 所在的 Activity 正确继承了 BaseActivity 并完成 recreate(),Fragment 的 onCreateView() 将自动使用新 Context 加载对应 values-fr/strings.xml 等资源——因为 getResources() 始终来自已更新的 Activity Context。
⚠️ 关键注意事项:
- ❌ 不要在 onResume() 中调用 updateConfiguration():此时 View 已渲染,部分组件(如 RecyclerView ViewHolder、AlertDialog)可能仍缓存旧资源;
- ✅ 必须在 attachBaseContext() 中完成 Locale 注入,这是 Android 资源加载链的起点;
- ✅ recreate() 是必需的,它会销毁并重建 Activity,从而触发新的 attachBaseContext 流程;
- ✅ 若使用 Jetpack Navigation 或动态 Feature Module,确保目标 Fragment 所在 Activity 同样继承 BaseActivity;
- ? 对于已存在的 Fragment 实例(如 setRetainInstance(true) 或 ViewModel 持久化场景),语言变更后需手动刷新 UI(例如调用 requireActivity().recreate() 或监听语言变更事件并重设文本)。
? 进阶建议:结合 ConfigurationCompat 和 AppCompatDelegate.setDefaultNightMode() 可统一管理语言 + 主题双配置;若需支持多语言 APK 分包(如 Android App Bundle),请确保 resConfig 在 build.gradle 中声明所有目标语言(resConfigs "en", "fr")。
遵循以上方案,即可实现全应用范围内一致、可靠的语言热切换,彻底解决 Fragment 语言不同步问题。











