如何将首选项附加到特定的 SharedPreferences?
我正在努力实现我们应用程序的首选项。我知道如何显示首选项 UI 以及如何使用 SharedPreferences
读取/写入值。在我们的应用程序中,我需要处理两组首选项,我想询问这个问题,特别是 Android 文档中的一条评论。
Preference.getSharedPreferences() 的文档有返回值
部分下的以下注释:
Returns
此 Preference 读取其值的 SharedPreferences,如果未附加到某个值,则返回 null偏好层次结构。
我想问如何将 SharedPreferences
附加到特定的 Preference
,无论是 EditTextPreference
还是其他。换句话说,Preference 中的持久性代码如何知道它应该将用户输入存储在一个特定的 SharedPreferences 对象中而不是另一个对象中?
为了用一个例子进一步解释我的问题,假设我有以下问题:
SharedPreferences prefs1 = getSharedPreferences(file1, mode);
SharedPreferences prefs2 = getSharedPreferences(file2, mode);
我的问题是我应该使用什么 API,以便 Prefs1
被 Preference
对象的持久性代码使用,并且不是 prefs2
。
目标是运行 2.3.4 的 Nexus One。
也许答案是显而易见的,但在阅读文档和搜索网络后我找不到它。预先感谢您的帮助。
I am working on implementing the preferences for our application. I know how to display preferences UI and how to read/write values using SharedPreferences
. In our app, I need to handle two sets of preferences and I would like to ask about this issue, one comment in the Android documents in particular.
The documentation for Preference.getSharedPreferences() has the following comment under the Return values
section:
Returns
The SharedPreferences where this Preference reads its value(s), or null if it isn't attached to a Preference hierarchy.
I would like to ask how it is possible to attach a SharedPreferences
to a particular Preference
, be it EditTextPreference
or others. In other words, how does the persistence code in a Preference
know that it should store the user input in one particular SharedPreferences
object and not the other?
To explain my question further with an example, suppose I have the following:
SharedPreferences prefs1 = getSharedPreferences(file1, mode);
SharedPreferences prefs2 = getSharedPreferences(file2, mode);
My question is what API I should use so that prefs1
is used by the Preference
objects' persistence code and not prefs2
.
The target is Nexus One, running 2.3.4.
Maybe the answer is obvious but I could not find it after reading the documentation and searching the web. Thank you in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Preference
使用PreferenceManager
的getSharedPreferences()
,最终路由到getDefaultSharedPreferences()
。欢迎您创建自己的
Preference
子类来更改此行为,但由于首选项屏幕系统可能未设计为处理多个SharedPreference
对象,因此您的首选项有可能会改变更改可能不会持久。IOW,我鼓励您重新考虑:
Preference
usesPreferenceManager
'sgetSharedPreferences()
, which eventually routes togetDefaultSharedPreferences()
.You are welcome to create your own
Preference
subclasses that change this behavior, but since the preference screen system may not be designed to handle multipleSharedPreference
objects, there's a chance that your preference changes might not get persisted.IOW, I encourage you to reconsider: