Android CheckBoxPreference - 取消/检查所有首选项
我有一个仅包含 CheckBoxPreferences
(要选择的类别)的 PreferenceScreen
。我需要一个选项来选中/取消选中所有这些。我有以下代码可以完成这项工作,但有一个问题:屏幕上的复选框未更新 - 我需要在视图或其他内容上调用一些 invalidate 。
这是我现在的代码:
private void checkAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, true);
}
editor.commit();
}
private void uncheckAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, false);
}
editor.commit();
this.restart();
}
该代码工作正常,但我需要以某种方式刷新视图才能立即查看结果(不仅仅是在关闭并重新启动设置活动之后)。
谢谢大家的建议!
I have a PreferenceScreen
containing only CheckBoxPreferences
(categories to select). I need an option to check/uncheck all of them. I have the following code that does the job but there is one problem: checkboxes on the screen are not updated - I'd need to call some invalidate on the view or something.
Here is my present code:
private void checkAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, true);
}
editor.commit();
}
private void uncheckAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, false);
}
editor.commit();
this.restart();
}
This code works fine but I'd need to refresh the view somehow to see the result imediatelly (not just after closing and re-starting the settings activity).
Thank You all for any advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您实际上并没有获取首选项对象,而只是获取实际值。在 for 循环中尝试一下:
我认为您可以省略调用编辑器并提交,因为 setChecked() 会为您执行此操作。
也检查这个。
That's because you're not actually grabbing the preference objects, just the actual values. Try this in your for loops:
I think you can omit calling the editor and committing, as the setChecked() will do that for you.
Check this out as well.
现在我有了这个工作代码,也许它会对某人有所帮助:
Now I have this working code, maybe it will help somebody: