如何强制 PreferenceActivity 处理我的 SharedPreferences?
我使用 SharedPreferences
来存储应用程序中所有Activities
的数据。我可以这样访问它:
SharedPreferences mSharedPreferences = getSharedPreferences("MyPrefs", 0);
我已经实现了 PreferenceActivity
因此用户可以通过它更改值,但它碰巧不是将数据读/写到“MyPrefs”而是:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
这对我来说有点意外。是否可以强制 PreferenceActivity
处理我的“MyPrefs”首选项?在单个应用程序中拥有多个首选项有什么意义?谢谢。
I'm using SharedPreferences
to store my data across all Activities
within my application. I get access to it like this:
SharedPreferences mSharedPreferences = getSharedPreferences("MyPrefs", 0);
I've implemented PreferenceActivity
so users can change values through it but it happens it reads/writes data not to "MyPrefs" but to:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Which is a bit unexpected for me. Is that possible to force PreferenceActivity
to deal with my "MyPrefs" preferences? And what is the point to have several preferences within single application? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可能的而且简单的。这对我有用
It is possible and simple. This worked for me
我建议在任何地方都使用 PreferenceManager.getDefaultSharedPreferences(context) ,这与首选项活动所使用的相同。但是,如果您需要坚持当前的设置,那么一个 hacky 解决方案(但我知道的唯一一个)是重写 getSharedPreferences 以返回您想要的内容。
I'd recommend just using PreferenceManager.getDefaultSharedPreferences(context) everywhere, which is the same as what the preference activity is using. But if you need to stick with your current setup then a hacky solution (but the only one I know of) is to override getSharedPreferences to return what you want.
没关系,只要您不打算使用
PreferenceActivity
即可。哎呀。
另外,删除那里的
getApplicationContext()
,除非您有特定原因使用Application
而不是活动/服务/其他内容。仅在必要时才使用Application
对象,并且您知道为什么必须这样做。不轻易。除非您有特殊原因要创建自己的
SharedPreferences
文件,否则我会使用默认文件。您可能有一个可重用的库或组件想要在 SharedPreferences 中存储内容,并且可能有自己的文件,以免弄乱托管应用程序的任何首选项。话虽如此,通常不需要多个首选项文件。
That's fine, so long as you weren't planning on using
PreferenceActivity
.Oops.
Also, get rid of
getApplicationContext()
there, unless you have a specific reason for using theApplication
rather than the activity/service/whatever. Only use theApplication
object when you have to and you know why you have to.Not readily. Unless you have some specific reason to invent your own
SharedPreferences
file, I'd use the default one.You might have a reusable library or component want to store stuff in
SharedPreferences
, and that might have its own file so as not to mess up any preferences from the hosting application. That being said, multiple preference files is not typically needed.