如何在选择每个选项的情况下初始化多选警报对话框?

时间:2016-11-20 02:42:01

标签: android listview alertdialog

目前我有一个带有多个选择框的警告对话框,我想在用户打开对话框时检查所有选择框。我已经进行了搜索,但是在没有首先显示对话框的情况下找不到选择所有选择框的方法。

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.custom_dialog);
    builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
            if (isChecked) {
                selectedItems.add(indexSelected);
            }
            else if (selectedItems.contains(indexSelected)) {
                selectedItems.remove(Integer.valueOf(indexSelected));
            }
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
         // TODO
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

            filterDialog.dismiss();
        }
    });
    filterDialog = builder.create();
    filterDialog.show(); // only works when I show the dialog first, but I want every option to be selected without showing first
    ListView list = filterDialog.getListView();
    for (int i = 0; i < list.getCount(); i++) {
        list.setItemChecked(i, true);
        selectedItems.add(Integer.valueOf(i));
    }
}

这将立即打开对话框并选择所有选择框。有没有办法选择所有框而不先显示对话框?

1 个答案:

答案 0 :(得分:2)

您可以像这样发送构建器参数中的已检查项目,

boolean[] checkedItems = new boolean[items.lengthh];

for (int i = 0; i < items.length; i++) {
    if (selectedItems.contains(i)) {
        checkedItems[i] = true;
    } else {
        checkedItems[i] = false;
    }
}

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
                if (isChecked) {
                    selectedItems.add(indexSelected);
                }
                else if (selectedItems.contains(indexSelected)) {
                    selectedItems.remove(Integer.valueOf(indexSelected));
                }
            }
        }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                // TODO
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {

                filterDialog.dismiss();
            }
        });