I have an application where the user can chose between several different colored themes from a PreferenceActivity
and thereby change the theme / color of the entire application. But the changes selected in the PreferenceActivity
do not apply immediately. The changes are applied only when the user reenters the PreferenceActivity
.
I know I can call recreate()
every time a theme is chosen, but I want to know if a better solution exists without recreating the entire activity.
Here is an video of how it currently works: https://www.youtube.com/watch?v=oU8xIUi_48A
This is where I set the chosen value from the preferenceList in my PreferenceActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
setTheme();
themecolorList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
switch (themecolorList.getValue()) {
case "grey":
themecolorList.getEditor().putString("grey", "green").apply();
break;
case "green":
themecolorList.getEditor().putString("green", "green").apply();
setTheme(R.style.AppTheme_default);
break;
case "blue":
themecolorList.getEditor().putString("blue", "green").apply();
break;
case "yellow":
themecolorList.getEditor().putString("yellow", "green").apply();
break;
case "red":
themecolorList.getEditor().putString("red", "green").apply();
break;
case "pink":
themecolorList.getEditor().putString("pink", "green").apply();
break;
default:
themecolorList.getEditor().putString("green", "green").apply();
break;
}
recreate();
return true;
}
});
}
The method setTheme();
is called in my PreferenceActivitys onCreate();
method
private void setTheme() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
switch (sharedPreferences.getString("THEME_KEY", "green")) {
case "grey":
setTheme(R.style.AppTheme_Grey);
break;
case "green":
setTheme(R.style.AppTheme_default);
break;
case "blue":
setTheme(R.style.AppTheme_Blue);
break;
case "yellow":
setTheme(R.style.AppTheme_Yellow);
break;
case "red":
setTheme(R.style.AppTheme_Red);
break;
case "pink":
setTheme(R.style.AppTheme_Pink);
break;
default:
getApplication().setTheme(R.style.AppTheme_default);
setTheme(R.style.AppTheme_default);
break;
}
}