我有一个CheckBox对话框,每次我在对话框中选择一些项目然后关闭对话框,然后重新打开对话框,我之前选择的所有项目都消失了。
这是我的代码
set_repeat_days = (LinearLayout)findViewById(R.id.repeat_days);
set_repeat_days.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final ArrayList<Integer> mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
String[] days = new String[]{"Monday", "Thursday", "Wednesday", "Tuesday", "Friday", "Saturday", "Sunday"};
final boolean[] checkedDays = new boolean[]{true, true, true, true, true, true, true};
builder.setMultiChoiceItems(days, checkedDays, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
if (isChecked){
mSelectedItems.add(which);
}else if (mSelectedItems.contains(which)){
mSelectedItems.remove(Integer.valueOf(which));
}
}
});
// Specify the dialog is not cancelable
builder.setCancelable(false);
builder.setTitle("Repeat");
// Set the positive/yes button click listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
// Set the neutral/cancel button click listener
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
答案 0 :(得分:1)
您可以使用这两个功能来保存和加载数据。
private void save(final boolean[] isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Integer i = 0; i < isChecked.length; i++)
{
editor.putBoolean(i.toString(), isChecked[i]);
}
editor.commit();
}
private boolean[] load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
boolean [] reChecked = new boolean[itemChecked.length];
for(Integer i = 0; i < itemChecked.length; i++)
{
reChecked[i] = sharedPreferences.getBoolean(i.toString(), false);
}
return reChecked;
}