如何从 android 中的另一个类获取 PreferenceActivity 的 SharedPreferences?
我是安卓新手。我对sharedPreference有一点了解。有些教程说在 xml 文件中添加首选项,但我需要动态添加首选项。所以我从 java 类(我的设置页面)完成了这一点。
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
现在,现在我需要从该设置页面获取所有选定复选框的标题(true)以显示选择了哪个选项。
我怎样才能做到这一点? 谢谢。
I'm new at android. I have a little idea over sharedPreference. Some tutorials say to add preferences in a xml file, but I need to add preferences dynamically. So I done that from a java class(my settings page).
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
Now, Now I need to get title of all selected checkbox (true) from that settings page to show which option been selected.
How can I do that?
thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用常规复选框和共享首选项。只需添加这样的状态
,然后当您需要拉取首选项状态时,只需执行即可,
然后您可以使用 if 语句来查看检查是 true 还是 false 等。
you can use a regular checkbox and sharedPreferences. Just add it's state like this
then when you need to pull the preference state, just do
then you can use an if statement to see if checked is true or false, etc.
从您所说的来看,听起来您所需要的只是您将使用的首选项的默认值。具体来说,您可能有一堆想要使用的复选框首选项。当您阅读它们时,您可以使用 getBoolean 方法来获取它们的值。
请注意,getBoolean 方法采用第二个参数,这是要返回的默认值。
这意味着您不必动态设置首选项。您使用 getBoolean 读取首选项,如果用户尚未设置首选项,则将返回您指定的默认值。
From what you're saying, it sounds like all you need is a default value for the preferences you will be working with. To be specific, you may have a bunch of checkbox-preferences that you want to use. When you read them, you can use the getBoolean method to get their values.
Note that the getBoolean method takes a second argument, which is the default value to return.
This means that you don't have to set the preferences dynamically. You use getBoolean to read the preferences and if the preferences have not been set by the user, a default value that you specify will be returned.