If you are using a piece of code that restarts the Activity inside onCreate()
, then it makes perfect sense that you are getting a restart loop. Every time your Activity is created, it restarts. Modify your code as such:
public class ThemeChanger
{
public final static int THEME_DARKORANGE = 0;
public final static int THEME_GREEN = 1;
public final static int THEME_BLUE = 2;
public final static int THEME_LIGHT = 3;
public static void restartActivity(Activity activity)
{
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
public static void onActivityCreateSetTheme(Activity activity, int newTheme)
{
switch (newTheme)
{
default:
case THEME_DARKORANGE:
activity.setTheme(R.style.Theme_Darkorange);
break;
case THEME_GREEN:
activity.setTheme(R.style.Theme_Green);
break;
case THEME_BLUE:
activity.setTheme(R.style.Theme_Blue);
break;
case THEME_LIGHT:
activity.setTheme(R.style.Theme_AppCompat_Light);
}
}
}
There is no need to use sTheme
since the theme is already stored in SharedPrefs. I renamed your changeToTheme()
method to restartActivity()
so it accurately reflects its purpose.
When you save your values, you should restart your Activity using the method we modified.
case R.id.bluetheme:
editor.putInt("mytheme", ThemeChanger.THEME_BLUE);
editor.commit();
ThemeChanger.restartActivity(this);
return true;
case R.id.darkorangetheme:
editor.putInt("mytheme", ThemeChanger.THEME_DARKORANGE);
editor.commit();
ThemeChanger.restartActivity(this);
return true;
case R.id.greentheme:
editor.putInt("mytheme", ThemeChanger.THEME_GREEN);
ThemeChanger.restartActivity(this);
editor.commit();
return true;
//etc.
restartActivity()
should only be used here, never in onCreate()
. This means that onCreate()
needs to use onActivityCreateSetTheme()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
int defaultValue = R.drawable.blue;
int themedefault = ThemeChanger.THEME_BLUE;
appliedtheme = preferences.getInt("mytheme", themedefault);
ThemeChanger.onActivityCreateSetTheme(this,appliedtheme);
setContentView(R.layout.main);
//rest of code
}