Save SWITCH button state, and recover state with SharedPrefs

我的梦境 提交于 2020-01-30 03:27:10

问题


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:


  1. findviewbyid will crash unless called after the view is created ie, in the oncreate method.
  2. Consider using click listener on your switches.
  3. I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
  4. Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!