You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用切换日夜模式时语言自动变更,该如何解决?

问题根因

当调用AppCompatDelegate.setDefaultNightMode()切换日夜模式时,会触发应用界面重建,重建过程中系统会默认使用系统Locale配置刷新资源,你之前手动设置的自定义语言配置会被覆盖,因此出现语言自动变更的问题。

解决方案

你需要保证自定义语言配置在每次资源初始化的时候都会被重新应用,不能仅在用户手动切换语言时设置一次,按以下步骤修改即可:

    1. 封装全局语言应用方法,兼容不同Android版本
      把原来的语言设置逻辑封装成可全局调用的工具方法,兼容新旧系统API:
public static Context applySavedLanguage(Context context) {
    // 读取你之前存在SharedPreferences里的自定义语言
    SharedPreferences sp = context.getSharedPreferences("你的SP存储文件名", Context.MODE_PRIVATE);
    String savedLang = sp.getString("Language", Locale.getDefault().getLanguage());
    Locale targetLocale = new Locale(savedLang);
    Locale.setDefault(targetLocale);

    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        configuration.setLocale(targetLocale);
        LocaleList localeList = new LocaleList(targetLocale);
        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);
    } else {
        configuration.locale = targetLocale;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return context.createConfigurationContext(configuration);
    } else {
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }
}
    1. 在Application的onCreate中调用该方法
      应用启动时就应用自定义语言配置:
public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        applySavedLanguage(this);
        // 其余应用初始化逻辑
    }
}
    1. 统一重写Activity的attachBaseContext方法
      创建公共BaseActivity,所有业务Activity继承该类,在界面重建时自动应用语言配置:
public class BaseActivity extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(applySavedLanguage(newBase));
    }
}
    1. 调整原有语言切换逻辑
      用户手动切换语言后,重启所有前台Activity让配置生效即可,原有存储逻辑不需要修改。

内容的提问来源于stack exchange,提问作者Ahmed Laggoun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:45:04