如何在不重新启动活动的情况下切换主题(夜间模式)?

如何在不重新启动活动的情况下切换主题(夜间模式)?

问题描述:

我制作了一些支持多个主题的应用程序,但是当用户切换主题时,我总是不得不重新启动该应用程序,因为setTheme()需要在setContentView()之前调用.

I have made a few apps that support multiple themes, but I always had to restart the app when user switches theme, because setTheme() needs to be called before setContentView().

我对它还可以,直到我发现了这个应用程序.它可以在两个主题之间进行无缝切换,也可以进行过渡/动画!

I was okay with it, until I discovered this app. It can seamlessly switch between two themes, and with transitions/animations too!

请给我一些有关如何实现(以及动画)的提示.谢谢!

Please give me some hints on how this was implemented (and animations too). Thanks!

@Alexander Hanssen的答案基本上已经回答了这个问题... 不知道为什么不接受它……可能是因为finish()/startActivity(). 我投了赞成票,但我尝试发表评论,但不能...

@Alexander Hanssen's answer basically has answered this... Don't know why it was not accepted... Maybe because of the finish()/startActivity(). I voted for it and I tried to comment but cannot...

无论如何,我会按照他所说的风格去做.

Anyway, I would do exactly what he described in terms of styles.

<style name="AppThemeLight" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>
<style name="AppThemeDark" parent="Theme.AppCompat">
    <!-- Customize your theme here. -->
    <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>
<!-- This will set the fade in animation on all your activities by default -->
<style name="WindowAnimationTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

但不是用新的意图完成/开始:

But instead of finish/start with new intent:

Intent intent = new Intent(this, <yourclass>.class);
startActivity(intent);
finish();

我会做的:

@Override
protected void onCreate(Bundle savedInstanceState) {

    // MUST do this before super call or setContentView(...)
    // pick which theme DAY or NIGHT from settings
    setTheme(someSettings.get(PREFFERED_THEME) ? R.style.AppThemeLight : R.style.AppThemeDark);

    super.onCreate(savedInstanceState);
}

// Somewhere in your activity where the button switches the theme
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // decide which theme to use DAY or NIGHT and save it
        someSettings.save(PREFFERED_THEME, isDay());

        Activity.this.recreate();
    }
});

效果如视频中所示...

The effect is as shown in the video...