Keeping active state in Android?
2 answers
So, for example, you can keep a color like this (I just put a hex reference for the color, but you can change it to whatever you want):
public void setBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("color", "#FFFFFF");
editor.commit();
}
Then just make sure you call this method every time it loads / reloads:
public void getBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
if (sharedPreferences.contains("color")) {
String myColor = sharedPreferences.getString("color", null);
mybackground.setBackgroundColor(Color.parseColor(myColor));
}
}
+3
source to share
Andy The answer is correct. However, I thought I would be responsible for saving and loading preferences. These are generic Save / Load methods for strings. This is what I use in all my actions. This could save you a lot of headaches down the road!
public static String PREFS_NAME = "random_pref";
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREF_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME , 0);
String value = settings.getString(key, "");
return value;
}
+2
source to share