如何在没有额外变量的情况下保存复选框的状态?
我在 6 个活动中有超过 100 个不同的复选框,我想保存每个活动的状态,这样当我从一个活动切换到另一个活动时,它仍然处于选中状态。我真的需要创建超过 100 个布尔值来单独保存每个复选框,还是有更简单的方法来保存和读出状态?我想过使用循环,但我真的想不出一种明智的方法来做到这一点。如果有人能提供帮助,那就太好了! 这是我的复选框之一的示例:它应该在单击该框时将一个字符串添加到 ArrayList 对象,并在取消选中该框时删除该字符串。它工作正常,但是当我离开时。 Actvity1,进入 Activity2,然后返回 Acivity1 取消选中我的一个复选框,该字符串会再次添加到我的 ArrayList 中,而不是被删除。
myBox1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (myBox1.isChecked() == true)
helperActivity.myStringArrayList.add("myString1");
else {
helperActivity.myStringArrayList.remove("myString1");}
}
});
I have over 100 different checkboxes in 6 activites and i would like to save the state of each, so that when i switch from one activity to another, it remains checked. Do i really have to create over 100 booleans to save each checkbox separately or is there an easier way to save and read out the states? I thought of using a loop but i cant really think of an intelligent way to do this. Would be great if anyone could help!
This is an example of one of my checkboxes: Its supposed to add a String to an ArrayList object when the box gets klicked and delete the String when the box gets unchecked. It works fine, but when i leave eg. Actvity1, go into Activity2 and come back to Acivity1 to uncheck one of my checkboxes, the string is added to my ArrayList a second time instead of beeing removed.
myBox1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (myBox1.isChecked() == true)
helperActivity.myStringArrayList.add("myString1");
else {
helperActivity.myStringArrayList.remove("myString1");}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种选择是使用共享首选项来保存每个复选框的选中状态。
此方案的优点是这些设置将在应用程序重新启动后继续存在。
One option would be to use Shared Preferences to save the checked state for each of your checkboxes.
The advantage of this scheme is that these settings will survive application restarts.
如果复选框的数量相同,则保留一个布尔数组
If the count of checkboxes is the same, keep a boolean array
您可以使用全局 HashMap 将复选框的 id 映射到它的状态。然后,您对 Checkbox 进行子类化,根据需要进行重写以将状态保存/恢复到 Map 中,并在 xml 文件中使用您的类。
然后,您可以在应用程序启动时保存和恢复地图,使用它写入文件:
并从其中读取:
从我的想法来看,我认为这是最好的方法。
You could map the id of the checkbox to it's state using a global HashMap. Then you subclass Checkbox, overriding as needed to save/restore the state into the Map, and use your class in the xml files instead.
You could then save and restore the Map when the app starts, use this to write to a file:
And this to read from one:
From the top of my head I think this is the best way.