在AlertDialog上保留多个选项清单

时间:2014-10-14 11:22:49

标签: java android sharedpreferences alertdialog

我正在使用带有多个选项的alertdialog。并且我想存储选定的值,以便当用户返回到alertdialog时,仍会检查之前选择的值。我的代码:

public class TimelineSettings extends DialogFragment {

final ArrayList selected_categories = new ArrayList();
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor sharedPrefEditor;
final CharSequence[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"};
boolean[] itemsChecked = new boolean[items.length];
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Set the dialog title
    builder.setTitle("Choisissez vos paramètres")
            // Specify the list array, the items to be selected by default (null for none),
            // and the listener through which to receive callbacks when items are selected
            .setMultiChoiceItems(items, null,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int indexselected,
                                            boolean isChecked) {
                            itemsChecked[indexselected] = isChecked;

                            if (isChecked) {
                                // If the user checked the item, add it to the selected items
                                selected_categories.add(indexselected);
                            } else if (selected_categories.contains(indexselected)) {
                                // Else, if the item is already in the array, remove it
                                selected_categories.remove(Integer.valueOf(indexselected));
                            }
                        }
                    })

                    // Set the action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // User clicked OK, so save the mSelectedItems results somewhere
                    // or return them to the component that opened the dialog

                }
            })
            .setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    return builder.create();
}

}

有没有办法用sharedpreferences(存储arraylist)来做?与this回答相同。

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用SharedPreferences将数据保存为ArrayList,如this answer

所示

答案 1 :(得分:0)

解决了问题。 here是解决方案和解释的答案。