将prefs.xml中的自定义SharedPreferences和首选项保留在同一位置



我使用这个方法来获得程序设置的SharedPreferences

public static SharedPreferences getPrefs(final Context context) {
    return context.getSharedPreferences(context.getPackageName()
            + "_preferences", Context.MODE_WORLD_READABLE);
}

我还在PreferenceActivity中使用prefs.xml,如下所示:

addPreferencesFromResource(R.xml.prefs);

我想将所有应用程序首选项存储在同一个位置(最好是:context.getPackageName() + "_preferences")),我该怎么做?

您为共享首选项文件选择的名称是默认共享首选项的名称,这最终会很糟糕。偏好片段的文档显示

当用户与这些首选项交互时,这些首选项将自动保存到SharedPreferences。要检索此活动中的首选项层次结构将使用的SharedPreferences实例,请调用getDefaultSharedPreferences(android.content.Context),并在与此活动相同的包中使用上下文。

从中加载首选项的xml与保存它们的xml无关。

因此,使用getDefaultSharedPreferences()不要混淆共享首选项的文件名,阅读引用的java文档(或多或少适用于PreferenceActivity),并查看:

  • getDefaultSharedPreferences和getSharedPreferences之间的差异
  • 共享首选项存储在哪里
  • 如何从Android中的首选项活动中获取SharedPreferences
  • 当您还没有';t设置文件名

最新更新