如何保存应用程序的设置? [英] How to save app settings?

查看:106
本文介绍了如何保存应用程序的设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能挽救我的应用程序的设置?眼下,例如,我有一个切换按钮开启/关闭。但是,如果我重新启动我的电话,切换按钮重新打开。它不保存设置,如果我完全关闭该应用程序。可我喜欢的设置到手机上保存的Cookie吗?

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 not saving the settings if I completely close the app. Can I like the save the settings to the phone as cookies?

推荐答案

使用共享preferences 。像这样:

在类的顶部将这个:公共静态最后弦乐我的preF =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
}

注意::您可以使用布尔做到这一点整数

所有你需要做的是改变字符串存储和读取到布尔,或任何类型你想要的。

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

下面是一个链接到一个pastie与code以上修改为存储布尔来代替:的 http://pastie.org/8400737

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

这篇关于如何保存应用程序的设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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