在 AndroidX 中使用区域设置和夜间模式更改发生冲突

问题描述

我尝试使用夜间模式并更改应用程序中的语言环境(使用 appcompat:1.1.0 和 appcompat:1.2.0 版本),但是当活动再次开始时,语言环境没有实现任何更改。这是我的代码

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(updateBaseContextLocale(base));
}


@TargetApi(Build.VERSION_CODES.N)
private Context updateResourcesLocale(Context context,Locale locale) {
    Configuration configuration = context.getResources().getConfiguration();
    configuration.setLocale(locale);
    return context.createConfigurationContext(configuration);
}
private Context updateBaseContextLocale(Context context) {
    String language = LocaleHelper.getLanguage(context); // Helper method to get saved language from SharedPreferences
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResourcesLocale(context,locale);
    }

    return updateResourcesLocaleLegacy(context,locale);
}
@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context,Locale locale) {
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration,resources.getdisplayMetrics());
    return context;
} 

我也尝试添加内容,但什么也没发生

@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
    if (overrideConfiguration != null) {
        int uiMode = overrideConfiguration.uiMode;
        overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration());
        overrideConfiguration.uiMode = uiMode;

    }
    super.applyOverrideConfiguration(overrideConfiguration);
}

我像这样更改主题AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)