Search code examples
androidcheckboxdialogoncheckedchanged

Android Checkbox asking confirmation twice when unchecking


I have a CheckBox in my code and if it's checked, the user shouldn't be able to just uncheck it. This is why I decided to implement an onCheckedChangeListener on the Checkbox.

If it's checked and clicked then confirmation is asked, else no confirmation is asked. When confirmation is asked (through a Dialog) and the user cancels, the checkbox has to remain (or be set again to) checked. So I implemented "CheckBox.setChecked(true)" on clicking the cancel button and now my confirmation is asked twice. I don't know how to get rid of this.

Here's the relevant code:

    mEventAttendingCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {      
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                //do nothing
            } else {
                Context mContext = EventSingleViewActivity.this;
                final Dialog dialog = new Dialog(mContext);

                dialog.setCancelable(true);

                Button confirmButton = (Button) dialog.findViewById(R.id.confirmButton);    
                confirmButton.setOnClickListener(new View.OnClickListener() { 
                    @Override
                    public void onClick(View v){ 
                        //do something
                    }
                });


                Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);  
                cancelButton.setOnClickListener(new View.OnClickListener() { 
                    @Override
                    public void onClick(View v) { 
                        dialog.dismiss();
                        mEventAttendingCheckBox.setChecked(true);
                    }
                });


                dialog.show();

            }
        }
    });

Solution

  • Implement on CLickListener instead of onCheckChanged.. because on CLick is called only when user clicks it ,.. But OnCheckChanged gets called even when you say setChecked() in code...