在多选 AlertDialog 中更改预定义项目的值

Change values of predefined Items in Multichoice AlertDialog

我一直在尝试实现一个多选警报对话框,在大多数情况下,一切都清晰易懂,但警报对话框从布尔数组中获取项目的状态,并且所有项目都设置为 true。如果在 alertdialog 中选中,我不太清楚如何更改数组中项目的状态。

 private void showCategorySelectionDialog() {
        // Prepare the dialog by setting up a Builder.
        final String selectionTitle = "Show on map: ";
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(selectionTitle);

        final String[] categories = new String[]{"Camping grounds","Abandoned places","Nature areas","Lookout Points"};
        
        // Find the current map type to pre-check the item representing the current state.
        boolean[] checkedItems = new boolean[]{
                true,
                true,
                true,
                true
        };

        // Add an OnClickListener to the dialog, so that the selection will be handled.
        builder.setMultiChoiceItems(

                categories,
                checkedItems,
                new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                      //check which item is clicked and if it was true then set it as false.
                        if (isChecked && checkedItems[which] == true){
                            checkedItems[which]= false;
                        }else{
                      //If item was clicked and the value was false then set it as true.
                            checkedItems[which] = true;
                        }
                    }
                }
        );
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        // Build the dialog and show it.
        AlertDialog categoryDialog = builder.create();
        categoryDialog.setCanceledOnTouchOutside(true);
        categoryDialog.show();
    }

当前的解决方案不会更改值,我的假设是我以不正确的方式处理数组,但我不确定正确的方式。

由于您想在检查时更改数组中元素的值,因此您可以尝试将该值设置为与通过 onClick() 传递的 isChecked 变量相等方法。

检查下面的代码:

        // Add an OnClickListener to the dialog, so that the selection will be handled.
        builder.setMultiChoiceItems(
                categories,
                checkedItems,
                new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        checkedItems[which] = isChecked;
                    }
                }
        );