Android 保存开关按钮状态,并使用SharedPrefs恢复状态
我有一个设置类,用户可以决定订阅/取消订阅Parse Push中的频道 我想我已经弄清楚了,除了要恢复的部分,并在下次用户打开应用程序或更改状态时保持开关状态 有人能帮我保存状态,并切换到用户选择的开关吗Android 保存开关按钮状态,并使用SharedPrefs恢复状态,android,parse-platform,sharedpreferences,Android,Parse Platform,Sharedpreferences,我有一个设置类,用户可以决定订阅/取消订阅Parse Push中的频道 我想我已经弄清楚了,除了要恢复的部分,并在下次用户打开应用程序或更改状态时保持开关状态 有人能帮我保存状态,并切换到用户选择的开关吗 public class Settings extends Activity { /** * Called when the activity is first created. */ private Switch krspush, egspush; public static fina
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");
}
}
重写该活动类的onCreate方法,并尝试加载保存在SharedReferences中的值
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
OP更新了问题。是的,添加了我的问题以便更容易理解。但为什么是错误的?如果用户选择true怎么办?编辑:我想我需要一些检查?这是假的,以防偏好还不存在。所以我们说“如果它不在那里,请将开关设置为false”,当用户第一次安装应用程序并且尚未切换应用程序时,当然会出现这种情况。谢谢,这很有效!现在我只需要弄清楚如何连接这个(Settings.class和ParsePush.class),我自己使用Parse,但我还没有使用Push功能。几乎是我还没玩过的东西。如果这对您有帮助,请将其标记为正确答案!是的,当然!谢谢你的帮助!