我需要在多个fragment
文件(不能使用活动文件)中使用共享的首选项,我必须存储几行字符串。
如何在片段中初始化shared preferences
?我如何写/读它?
我是否需要在主活动中对其进行初始化,还是必须在片段活动文件中对其进行初始化?
技巧如:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
...不起作用。
最佳答案
尝试将您的SharedPreferences封装在一些首选项类中,类似于:
class MyPrefs {
private static final String FILENAME = "prefs_filename";
private static final String KEY_SOMETHING = "something";
private SharedPreferences mPreferences;
public MyPrefs(Context context) {
mPreferences = new SharedPreferences(FILENAME, Context.MODE_PRIVATE);
}
public void setSomething(Something value) {
mPreferences.edit().put...(KEY_SOMETHING, value).commit();
}
public Something getSomething() {
return mPreferences.getSomething(key, defaultValue);
}
}
这样,我们为非易失性数据存储提供了干净的API。
SharedPreferences
级别太低,暴露了太多细节,例如存储文件名,它迫使我们记住所有键和值类型以提取任何数据。在简单的情况下,它可能会起作用,但是一旦您存储的数据变得复杂,就会产生很多问题。尝试存储诸如用户配置文件之类的内容,其中包含很少的字段或简单的复数,您就会明白。使用原始的SharedPreferences
将使您的重构陷入痛苦。裸SharedPreferences
甚至简单的数据格式升级(如架构更新)也将很快变得不可能。关于java - 如何在多个 fragment 文件中使用共享首选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27091471/