Search code examples
androidcheckboxandroid-alertdialog

AlertDialog with CheckBox


In my application I have button to which displays an AlertDialog. The AlertDialog has a CheckBox. Now I have to call a function if the checkbox is checked, and a different function if its not checked.

        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme);

        builder.setTitle("Delete Completed Tasks:");
        View view = getLayoutInflater().inflate(R.layout.del_completed,null);

        builder.setView(view);

        builder.setPositiveButton("Delete",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        CheckBox cb = findViewById(R.id.checkbox);

                        if(cb.isChecked()){
                            helper.delCompAndRec();
                        }
                        else helper.delCompleted();
                    }
                });

        builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

The problem is I always get the cb.isChecked() value as False, even if its checked. How do I solve this?


Solution

  •         AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme);
    
            builder.setTitle("Delete Completed Tasks:");
            View view = getLayoutInflater().inflate(R.layout.del_completed,null);
            final CheckBox cb = view.findViewById(R.id.checkbox); //or declare as global variable
            builder.setView(view);
    
            builder.setPositiveButton("Delete",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            
                            if(cb.isChecked()){
                                helper.delCompAndRec();
                            }
                            else helper.delCompleted();
                        }
                    });
    
            builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
    
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
    
                }
            });
    
            AlertDialog alert = builder.create();
            alert.show();
        }