更改应用程序主题而不重新创建活动 [英] Changing app theme without recreating activity

查看:122
本文介绍了更改应用程序主题而不重新创建活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义主题,其中Theme.AppCompat.DayNight.NoActionBar作为父主题,具有昼夜模式的资源.

I have a custom theme with Theme.AppCompat.DayNight.NoActionBar as the parent with resources for both day and night modes.

文档中提供了一种更改主题的方法,除非重新创建当前活动,否则主题将仅在下次启动该活动时更改.

In the documentation, there is a method provided to change the theme and unless the current activity is recreated, the theme will only change the next time that activity is launched.

另一方面,Twitter和Pocket可以更改主题,而无需重新创建用户所在的活动.

Twitter and Pocket on the other hand change the themes without recreating the activity the user is on.

我该如何实现?

推荐答案

另一方面,Twitter和Pocket可以更改主题,而无需重新创建用户所在的活动.

Twitter and Pocket on the other hand change the themes without recreating the activity the user is on.

你怎么知道?如果您正确地处理了保存的状态并提供了看起来不像更改窗口的动画,则可以使活动重新娱乐看起来足够好.实际上,您可以使它看起来很好,甚至不知道该活动已被重新创建.

How do you know? If you handle saved state correctly and provide an animation that doesn't look like changing windows you can make activity recreation look good enough. In fact you can make it look so good that you even wouldn't recognize the activity was recreated.

在Twitter中切换夜间模式之前和之后,运行adb shell dumpsys activity会给出以下输出:

Running adb shell dumpsys activity gives the following output before and after toggling night mode in Twitter:

ResumedActivity: ActivityRecord{40c4156 u0 com.twitter.android/com.twitter.app.main.MainActivity t11398}
ResumedActivity: ActivityRecord{adca640 u0 com.twitter.android/com.twitter.app.main.MainActivity t11399}

请注意,活动哈希码已更改-该活动确实已重新创建.对于最新版本的Twitter和2016年11月9日发布的Twitter 6.22.1都是如此.

Notice the activity hash code changed - the activity did recreate. This is true for both a recent version of Twitter and for Twitter 6.22.1 published on Nov 9, 2016.

更改主题是一项艰巨的任务.您必须遍历整个视图层次结构,并更改所有背景颜色,文本颜色,波纹(祝您好运),并且您必须确保以后对getResources().get*将返回正确的资源.

Changing theme is a non-trivial task. You'd have to traverse the whole view hierarchy and change all the background colors, text colors, ripples (good luck with this one), and you'd have to make sure that any future call to getResources().get* will return the correct resources.

另一方面,您可以调用Activity.recreate()并让系统执行其已编程的操作.

On the other hand you could just call Activity.recreate() and let the system do what it's already programmed to do.

此后,您可以使用某些不会更改窗口大小和位置的动画来调用Activity.overridePendingTransition(...).有更多的方法可以对窗口过渡进行动画处理.

After that you could call Activity.overridePendingTransition(...) with some animations that don't change window size and position. There are more ways to animate the window transition.

这篇关于更改应用程序主题而不重新创建活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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