سؤال

I have created an application where i can switch between 2 themes( Black and white) by a button click. And I have set default theme as white in the manifest.

So every time the application is closed and restarted, the theme state is not saved and white theme is applied.

Can anyone give me some idea or code if possible, about how to save the state of the application, different methods to do it?

Thank You.

هل كانت مفيدة؟

المحلول

Have a boolean trigger that you check the SharedPreferences for. If the boolean is true, set the application to white. If false, black. Every time the user changes the theme he/she wants, save the boolean in the SharedPreferences.

Code Sample:

In onCreate():

SharedPreferences mPrefs = getSharedPreferences("THEME", 0);
boolean theme_boolean = mPrefs.getBoolean("theme_boolean", true);
if (theme_boolean) {
    // Set theme to white
} else {
    // Set theme to black
}

In the button's onClick():

if (theme_boolean) {
    // Set theme to black
    theme_boolean = false;
} else {
    // Set theme to white
    theme_boolean = true;
}
SharedPreferences mPrefs = getSharedPreferences("THEME", 0);
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putBoolean("theme_boolean", theme_boolean).commit();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top