Change Activity theme deppending on fragment in use Android

泪湿孤枕 提交于 2019-12-19 10:14:12

问题


I have an activity that switches between several fragments. This activity has a default style, but when i change to some particular fragments i want it to change the style. I've done some research and i got this code that i run in the onCreateView() of a fragment:

// create ContextThemeWrapper from the original Activity Context with the custom theme
    Context context = new ContextThemeWrapper(getActivity(), R.style.GreyTheme);
    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(context);
    // inflate using the cloned inflater, not the passed in default 

    View rootView = localInflater.inflate(R.layout.my_layout, container, false);

This code only works if the activity is restarted (eg: if i rotate the device it updates to the new style as i want). I think that it is not possible to switch between styles witout recreating an activity or am i wrong?


回答1:


Technically speaking: no.

You can not change the current theme if the Activity has been created.

This code only works if the activity is restarted (eg: if i rotate the device it updates to the new style as i want). I think that it is not possible to switch between styles witout recreating an activity or am i wrong?

As rotating includes a recreation of the activity, this is the reason on why is "working".

But… there is one application called Pocket (also Press and Firefox if I remember correctly) that does this in a clever way.

How to do it?

Basically the trick lies in this formula:

Base Color1 + Middle Color = Theme Color 1

Base Color2 + Middle Color = Theme Color 2

Keep in mind that Middle Color is the same. For the base color you have to put it to the Window holding your app instance, something like this:

getWindow().setBackgroundDrawable(new ColorDrawable(isLight ? Color.WHITE : Color.BLACK));

Therefore when is combined with an intermediate color, gives you two different themes.

Here you can see how you can do it (it explains the concept very well):

http://sriramramani.wordpress.com/2012/12/06/runtime-theme-change/

EDIT 1:

Added more explanations to the link posts



来源:https://stackoverflow.com/questions/23635824/change-activity-theme-deppending-on-fragment-in-use-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!