保存 SWITCH 按钮状态,并使用 SharedPrefs 恢复状态 [英] Save SWITCH button state, and recover state with SharedPrefs

查看:35
本文介绍了保存 SWITCH 按钮状态,并使用 SharedPrefs 恢复状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有人可以帮助我如何保存状态,并将 SWITCH 切换到用户选择的位置吗?

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

推荐答案

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

Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.

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

这篇关于保存 SWITCH 按钮状态,并使用 SharedPrefs 恢复状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆