Change Activity theme deppending on fragment in use Android

后端 未结 1 1321
时光取名叫无心
时光取名叫无心 2021-01-15 05:08

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.

1条回答
  •  不思量自难忘°
    2021-01-15 05:47

    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

    0 讨论(0)
提交回复
热议问题