This question already has an answer here:
- Implementing user choice of theme 3 answers
I've created a PreferenceActivity that allows the user to choose the theme he wants to apply to the entire application.
When the user selects a theme, this code is executed:
if (...) {
getApplication().setTheme(R.style.BlackTheme);
} else {
getApplication().setTheme(R.style.LightTheme);
}
But, even though I've checked with the debugger that the code is being executed, I can't see any change in the user interface.
Themes are defined in res/values/styles.xml
, and Eclipse does not show any error.
<resources>
<style name="LightTheme" parent="@android:style/Theme.Light">
</style>
<style name="BlackTheme" parent="@android:style/Theme.Black">
</style>
</resources>
Any idea about what could be happening and how to fix it?
Should I call setTheme
at any special point in the code? My application consists of several Activities if that helps.
recreate()
(as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.So, another solution for this problem is to recreate the task stack completely, like this:
EDIT:
Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method
setTheme()
called beforeonCreate()
, probably in some parent activity. It is also a normal approach to store the theme chosen inSharedPreferences
, read it and then set usingsetTheme()
method.I know that i am late but i would like to post a solution here: Check the full source code here. This is the code i used when changing theme using preferences..
If you want to change theme of an already existing activity, call
recreate()
aftersetTheme()
.Note: don't call recreate if you change theme in
onCreate()
, to avoid infinite loop.We have to set theme before calling 'super.onCreate()' and 'setContentView()' method.
Check out this link for applying new theme to whole application at runtime.
You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.
This is what i have created for Material Design. May it will helpful you.
Have a look for MultipleThemeMaterialDesign