如何在不重启活动的情况下切换主题(夜间模式)? [英] How to switch themes (night mode) without restarting the activity?

查看:54
本文介绍了如何在不重启活动的情况下切换主题(夜间模式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了几个支持多主题的应用,但是每次用户切换主题时总是要重启应用,因为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();
    }
});

效果如视频所示...

这篇关于如何在不重启活动的情况下切换主题(夜间模式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆