Search code examples
androidcheckboxandroid-alertdialogconfirmation

AlertDialog before selecting checkBox in Android


I have dialog with checkBox. Before selecting this checkBox i would like to ask user, that he is sure to select these checkBox. (I mean, I try to select checkBox and before this AlertDialog appear and ask whether I am sure)

In code it looks like this:

CheckBox cb = (CheckBox) v.findViewById(R.id.favouriteChkBox);

            if (cb.isChecked()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        context);
                builder.setTitle("Do you want to add this to favourite?");

                builder.setPositiveButton("yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                itemChecked.set(position, true);
                            }
                        });
                builder.setNegativeButton("no",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();
                            }
                        });
                builder.create().show();

            }

But this does not work. The AlertDialog is shown and no metter if I clicked "yes" or "no", checkBox is selected.

Can you tell me why this does not work? Thanks!


Solution

  •     final CheckBox cb = (CheckBox) findViewById(R.id.favouriteChkBox);
    
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cb.isChecked()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            TestGitActivity.this);
                    builder.setTitle("Do you want to add this to favourite?");
    
                    builder.setPositiveButton("yes",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    cb.setChecked(true);
                                }
                            });
                    builder.setNegativeButton("no",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    cb.setChecked(false);
                                }
                            });
                    builder.create().show();
    
                }
    
            }
        });