如何在 Android 中将 PreferenceActivity 中的 SharedPreferences 设置为默认值?

发布于 2024-10-05 08:15:23 字数 329 浏览 0 评论 0原文

我已经为 PreferenceScreen 创建了一个基于 xml 的 PreferenceActivity。在 xml 中,您可以为不同的首选项分配默认值。但在屏幕打开和关闭之前,这些不会存储在我的 SharedPreferences 中。

问题是我想立即使用存储在该屏幕中的首选项(例如服务器地址),并且用户只需要在想要更改默认值时打开它。

有没有一种方法可以存储首选项屏幕 xml 中的所有首选项,而不强制用户打开和关闭首选项 Activity?

我知道您可以在从 SharedPreferences 检索 Preference 时提供默认值,但必须在 xml 和代码中维护默认值是愚蠢的。

I have created a PreferenceActivity based on xml for PreferenceScreen. In the xml you can assign default values to the different preferences. But these are not stored in my SharedPreferences before the screen is opened and closed.

The problem is that I want to immediately use the Preferences stored in this screen (like server address), and the user will only need to open it if he wants to change the default values.

Is there a way to store all the preferences from the preferencescreen xml without forcing the user to open and close the preference activity?

I am aware that you can supply a default value when retrieving the Preference from SharedPreferences, but it is stupid to have to maintain default values both in xml and code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们的影子 2024-10-12 08:15:26

只需在 Application 类中使用此代码即可。

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

它将从 XML 加载您的首选项,最后一个参数 (readAgain) 将保证用户首选项不会被覆盖。您需要维护 R.xml.preference 文件中的默认参数。

查看 PreferenceManager.setDefaultValues 在 Android API 中进行进一步调查。

Just use this code in the Application class.

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten. You need to maintain the default parameters in the R.xml.preference file.

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文