问题
I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
回答1:
Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
回答2:
- findviewbyid will crash unless called after the view is created ie, in the oncreate method.
- Consider using click listener on your switches.
- I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
- Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
- You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html
来源:https://stackoverflow.com/questions/31007320/save-switch-button-state-and-recover-state-with-sharedprefs