我在6个活动中有超过100个不同的复选框,我想保存每个活动的状态,这样当我从一个活动切换到另一个活动时,它仍然被检查。我真的必须创建超过100个布尔值来单独保存每个复选框,还是有更简单的方法来保存和读出状态?我想过使用一个循环,但我真的不能想到一个聪明的方法来做到这一点。如果有人能帮忙的话会很棒! 这是我的一个复选框的示例:它应该在弹出框时向StringList对象添加一个String,并在取消选中该框时删除String。它工作正常,但当我离开时,例如。 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");}
}
});
答案 0 :(得分:0)
如果复选框的数量相同,请保留一个布尔数组
答案 1 :(得分:0)
您可以使用全局HashMap将复选框的ID映射到其状态。然后,您将Checkbox子类化,根据需要覆盖以将状态保存/恢复到Map中,并在xml文件中使用您的类。 然后,您可以在应用程序启动时保存并恢复Map,使用它来写入文件:
file = context.openFileOutput("checkbox_state.prefs", Context.MODE_PRIVATE);
objectOutputStream = new ObjectOutputStream(file);
objectOutputStream.writeObject(myCheckboxesState);
这是从一个人那里读的:
file = context.openFileInput("checkbox_state.prefs");
objectInputStream = new ObjectInputStream(file);
myCheckboxesState = (Map<Integer, Boolean>) objectInputStream.readObject();
从我的头脑中,我认为这是最好的方式。
答案 2 :(得分:0)
一种选择是使用Shared Preferences为每个复选框保存选中状态。
// Access the default SharedPreferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
...
SharedPreferences.Editor editor = preferences.edit();
// Save the checked state
editor.putBoolean("myBox1", true);
editor.commit();
...
// Get and set the checked state
boolean myBox1State = preferences.getBoolean("myBox1", false);
myBox1.setChecked(myBox1State);
此方案的优点是这些设置将在应用程序重新启动后继续存在。