How to save app settings?

前端 未结 6 1760
暖寄归人
暖寄归人 2020-12-07 03:01

How can I save the the settings of my app? Right now, for example, I have a togglebutton to turn on/off. But if I restart my phone, the toggle button is turned back on. Its

6条回答
  •  执笔经年
    2020-12-07 03:21

    Use Shared Preferences. Like so:

    Put this at the top of your class: public static final String myPref = "preferenceName";

    Create these methods for use, or just use the content inside of the methods whenever you want:

    public String getPreferenceValue()
    {
       SharedPreferences sp = getSharedPreferences(myPref,0);
       String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
       return str;
    }
    
    public void writeToPreference(String thePreference)
    {
       SharedPreferences.Editor editor = getSharedPreferences(myPref,0).edit();
       editor.putString("myStore", thePreference);
       editor.commit();
    }
    

    You could call them like this:

    writeToPreference("on"); // stores that the preference is "on"
    writeToPreference("off"); // stores that the preference is "off"
    
    if (getPreferenceValue().equals("on"))
    {
       // turn the toggle button on
    }
    else if (getPreferenceValue().equals("off"))
    {
       // turn the toggle button off
    }
    else if (getPreferenceValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
    {
       // a preference has not been created
    }
    

    Note: you can do this with boolean, integer, etc.

    All you have to do is change the String storing and reading to boolean, or whatever type you want.

    Here is a link to a pastie with the code above modified to store a boolean instead: http://pastie.org/8400737

提交回复
热议问题