AppCompatDelegate.setDefaultNightMode仅应用于当前的Activity,而不应用于整个应用程序

时间:2018-04-05 10:08:55

标签: android android-appcompat android-theme

我正在尝试从扩展PreferenceFragmentCompat的Fragment更改主题(白天或黑夜)。设置主题后,我调用activity.recreate()来应用主题,但它只更改当前屏幕的主题(当我按回旧的时,它们是可见的)。如果我调用activity.finish(),它会更改整个应用程序的主题。但我不想退出当前屏幕。知道怎么解决这个问题吗?提前致谢。

preferenceTheme.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                PreferencesUtils.setThemeDayOrNight(newValue.toString());
                Activity activity = getActivity();
                if(activity != null){
                    activity.recreate();
                }
                return true;
            }
        });

public static void setThemeDayOrNight(String themeValue) {
    if (themeValue.equalsIgnoreCase(THEME_DAY)) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了一个快速的解决方案,但不确定它是否是最好的。

使用来自之前的Activity和onActivityResult的startForActivityResult启动首选项活动返回到首选项活动,如下所示:

Intent intent = new Intent(this, MyPreferencesActivity.class);
            startActivityForResult(intent, RC_SETTINGS);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK && requestCode == RC_PREFERENCES) {
        // To be able to change theme from settings and stay in the same screen after it we need
        // to get if theme was changed and then return to settings screen

        if (resultCode == RESULT_OK && data.getBooleanExtra(SettingsActivity.EXTRA_CHANGE_THEME, false)) {
            Intent intent = new Intent(this, MyPreferencesActivity.class);
            startActivityForResult(intent, RC_SETTINGS);
        }
    }
}

在MyPreferencesActivity.class上:

preferenceTheme.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesUtils.setThemeDayOrNight(newValue.toString());

                if(activity != null) {
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra(EXTRA_CHANGE_THEME, true);
                    setResult(Activity.RESULT_OK, resultIntent);
                    activity.finish();
                }

                return true;
            }
        });