本文介绍了无法在DayNight主题中动态切换模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中实现了DayNight主题,并添加了在昼夜模式之间切换的设置,但是如果不重新启动,我将无法在模式之间动态切换.

I implemented the DayNight theme in my app and added a setting to switch between day and night mode, but I'm not able to switch between modes dynamically without a restart.

如果在更改设置后使用setDefaultNightMode(),则设置活动不会更改模式,但后堆栈中的活动会更改.如果我另外使用setLocalNightMode(),则将重新创建设置活动并更改其模式,但是现在堆栈中的活动不再.我找不到一种方法来完成这两项工作.有办法吗?

If I use setDefaultNightMode() after the setting has been changed, the settings activity doesn't change mode, but the activities in the backstack do. If I additionally use setLocalNightMode() the settings activity gets recreated and changes its mode, but now the activities in the backstack don't. I could not find a way to accomplish both. Is there a way to do this?

推荐答案

这是 CheeseSquare 存储库位于这里:

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

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

这是从V25开始的recreate()的描述.我似乎找不到此调用的其他文档-请注意,它是在V11中添加的.

Here is the description of recreate() as of V25. I can't seem to find other documentation for this call - note that it was added at 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.
 */

这篇关于无法在DayNight主题中动态切换模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:43