How to save checkbox value with shared preferences?

前端 未结 3 1228
你的背包
你的背包 2020-12-12 06:37

I don\'t know why my code not save checkbox checked value; if I check checkbox and after I click on another tab and comeback to previous tab,

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 07:42

    You can store boolean values on shared preferences. Here's an example.

    SharedPreferences myPrefs;
    SharedPreferences.Editor myPrefsPrefsEditor;
    static final String MY_SHARED_PREF = "name_of_your_shared_pref";
    

    Initialize your shared preferences

    myPrefs = this.getSharedPreferences(MY_SHARED_PREF, Context.MODE_PRIVATE);
    

    Store your values using the following.

    myPrefsPrefsEditor = myPrefs.edit();
    myPrefsPrefsEditor.putBoolean(key, value);
    myPrefsPrefsEditor.commit();
    

    key = use to find the value from shared pref

    value = the value you want to store

    This is how your read your values

    myPrefs.getBoolean(key, defaultValue);
    

    key = the key of the value you want to get

    defaultValue = the default value when there's no value for the given key.

    Hope this helps.

提交回复
热议问题