7

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!!

user2781627
  • 455
  • 5
  • 17

1 Answers1

10

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.

Xaver Kapeller
  • 49,491
  • 11
  • 98
  • 86
  • But using attrs.xml has to do something I mean attributes of a style can be changed?? – user2781627 Aug 25 '14 at 10:25
  • No that has nothing to do with it. XML attributes are loaded in `onCreate()` just like you would call `setTheme()` in `onCreate()` and just like with `setTheme()` you are not able to change it afterwards. – Xaver Kapeller Aug 25 '14 at 10:26