Lor*_*ic- 5 android default sharedpreferences
我想了解Android的SharedPreferences.我是初学者,不太了解它.
我有我为我的应用程序首选项实现的这个类
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我想设置默认首选项.它们将在安装应用程序时设置,并且可以在应用程序之后进行修改并保持持久性.我听说过一个preferences.xml,但我不明白这个过程.
有人能帮助我吗?
谢谢你的时间
很简单,如果你想为每个变量设一个单独的默认值,你需要为每个变量做一个,但是你的方法:
public String get(String key) {
return this.sharedPreferences.getString(key,"this is your default value");
}
Run Code Online (Sandbox Code Playgroud)
如果用户从未访问过变量或从未创建变量,系统会将默认值设置为值,如果您或用户更改了此值,则忽略默认值.请参阅 http://developer.android.com/guide/topics/data/data-storage.html#pref
直接来自Android文档:
SharedPreferences类提供了一个通用框架,允许您保存和检索原始数据类型的持久键值对.您可以使用SharedPreferences保存任何原始数据:布尔值,浮点数,整数,长整数和字符串.此数据将在用户会话中持续存在(即使您的应用程序被终止).
| 归档时间: |
|
| 查看次数: |
18711 次 |
| 最近记录: |