保存SWITCH按钮状态,并使用SharedPrefs恢复状态

时间:2015-06-23 15:39:54

标签: android parse-platform sharedpreferences

我有一个Settings类,因此用户可以决定订阅/取消订阅Parse Push中的频道。

我认为除了要恢复的部分以外,我完全弄明白了,并在下次用户打开应用程序或更改状态时保持切换状态。

有人可以帮我解决如何保存状态,并将SWITCH切换到用户选择的内容吗?

 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");
    }
}

2 个答案:

答案 0 :(得分:2)

覆盖该活动类的onCreate方法,并尝试加载您在SharedPreferences中保存的值。

krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));

答案 1 :(得分:0)

  1. findviewbyid会崩溃,除非在创建视图后调用,即在oncreate方法中。
  2. 考虑在交换机上使用点击侦听器。
  3. 我没有看到这行代码的重点" SharedPreferences sharedPrefs = getSharedPreferences(" SwitchButton",MODE_PRIVATE)"
  4. 以下是您使用共享偏好设置的方式:https://stackoverflow.com/a/23024962/2590252
  5. 您最好查看一些示例,以了解最佳编码实践http://developer.android.com/samples/index.html