问题描述
从我可以从 SharedPreferences 文档中获得的内容来看,我可以更新首选项、添加一个或清除共享首选项文件中的所有首选项值.
from what I can incur out of the SharedPreferences documentation, I can update a preference, add one or clear all preference values in a shared preference file.
但我想完全清除共享首选项文件中的所有内容,不仅仅是值,还有它们所引用的首选项.
But I want to completely clear everything inside a shared preference file, not just the values, but the preferences they refer to as well.
推荐答案
如果你有一个 SharedPreferences.Editor
对象并且你调用了 clear()
,这会不会得到你想要什么?它将删除所有首选项,如果您调用 sharedPref.getAll()
它应该会给您一个大小为 0 的地图 [我刚刚测试了这个].
If you have a SharedPreferences.Editor
object and you call clear()
, does this not get you what you want? It will remove all preferences and if you call sharedPref.getAll()
it should give you a map of size 0 [I just tested this].
要删除一个特定的首选项,请调用 editor.remove(pref)
,其中 pref 是首选项名称.
To remove one specific preference, call editor.remove(pref)
, where pref is the preference name.
PS:不要忘记通过在编辑器上调用 commit() 或 apply() 方法来提交更改.apply() 更快,因为它是异步的.commit() 是同步的,但返回一个布尔值,指示提交是否成功.
PS: Don't forget to commit your changes by calling commit() or apply() method on the editor. apply() is faster as it is asynchronous. commit() is synchronous but returns a boolean indicating if the commit succeeded.
这篇关于清除 Android 中 SharedPreferences 中的首选项,而不仅仅是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!