问题
I have an activity . In that on a button click I want to change the theme but everywhere I found that theme can be set only once and that too before setContentView. Restarting an activity is not an option for me. Maybe using attrs has to do something with this problem. But I have no idea how to use it. Please Help!!
Thanks in advance!!
回答1:
No that is not possible, from the relevant documentation:
public void setTheme (int resid)
Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).
So you have to set the theme with setTheme()
before calling setContentView()
, after that it is impossible to change it. Your only option is to recreate the Activity
.
As an aside: That you say that recreating the Activity
is not an option seems weird, Activities
have a well defined life cycle and by adhering to this life cycle it should be possible to recreate the Activity
how ever often you or the Android OS wants to. In fact you should know that your Activity
can be killed and recreated by the Android OS at any moment and this is in fact a normal and expected behaviour of Android. So that recreating the Activity
is not an option seems to indicate a much deeper rooted problem in your apps design that will manifest itself anyway if not solved.
来源:https://stackoverflow.com/questions/25483640/changing-theme-of-an-activity-without-recreating-activity