无法动态切换DayNight主题中的模式

时间:2017-01-18 16:38:30

标签: android themes android-support-library

我在我的应用程序中实现了DayNight主题,并添加了一个在白天和夜晚模式之间切换的设置,但是我无法在没有重启的情况下动态切换模式。

如果我在更改设置后使用setDefaultNightMode(),则设置活动不会更改模式,但是背板中的活动会执行此操作。如果我另外使用setLocalNightMode(),则会重新创建设置活动并更改其模式,但现在backstack中的活动不会。我无法找到实现两者的方法。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

以下是位于CheeseSquarehere回购邮件的MainActivity.java模块中的实施:

private void setNightMode(@AppCompatDelegate.NightMode int nightMode) {
    AppCompatDelegate.setDefaultNightMode(nightMode);

    if (Build.VERSION.SDK_INT >= 11) {
        recreate();
    }
}

以下是从V25开始重新创建()的说明。我似乎无法找到此电话的其他文档 - 请注意它已添加到V11。

/* Cause this Activity to be recreated with a new instance.  This results
 * in essentially the same flow as when the Activity is created due to
 * a configuration change -- the current instance will go through its
 * lifecycle to {@link #onDestroy} and a new instance then created after it.
 */

答案 1 :(得分:1)

我让它工作,这是我的代码和屏幕记录。 后台的活动也在改变他们的主题。

findPreference(getString(R.string.pref_key_night_mode)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if ((Boolean) newValue) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            }
            getDelegate().applyDayNight();
            recreate();
            return true;
        }

    });

record

<强>更新

上面的解决方案适用于Android 4.4,但在Android 7.1的backstack中保留了之前的DayNight状态。

我在onResume中添加了夜间模式设置更改的手动检查:

@Override
protected void onResume() {
    super.onResume();
    if (mApplyNightMode) {
        mApplyNightMode = false;
        getDelegate().setLocalNightMode(PeshkaPreferences.getNightModeEnabled(this) ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
        getDelegate().applyDayNight();
        recreate();
    }
}

并添加了OnSharedPreferencesChangeListener

protected OnSharedPreferenceChangeListener mPreferencesListener = new OnSharedPreferenceChangeListener() {

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(getString(R.string.pref_key_night_mode))) {
            mApplyNightMode = true;
        }
    }
};
相关问题