Search code examples
androidbuttonandroid-alertdialog

Dialog open twice on fast click of button


I have Button, which on clicking, displays a Dialog. Everything works like a charm, but if I double click the button or click the button fast, the Dialog opens two or three times. I have to click the back button twice or thrice to dismiss the Dialog.

I have searched for related questions on SO, but most of the answers suggest disabling the button or to use a variable and setting it to true and false, which is not my requirement.

If anyone knows how to solve this problem, please help me.

Code I have used

// Delete item on click of delete button
holder.butDelete.setOnClickListener(new OnClickListener() {         
@Override
    public void onClick(View v) {
        Dialog passwordDialog = new Dialog(SettingsActivity.this);      
        passwordDialog.show();
    }
});

Solution

  • You have to just check whether your Dialog is already shown or not:

    Dialog passwordDialog = new Dialog(SettingsActivity.this);
    holder.butDelete.setOnClickListener(new OnClickListener() {           
        @Override
        public void onClick(View v) {                  
            if(!passwordDialog.isShowing()) {
                passwordDialog.show();
            }
        }
    });
    

    Update:

    If this doesn't work in your case, then in your activity declare globally:

    Dialog passwordDialog = null;
    

    and on Button's click:

    holder.butDelete.setOnClickListener(new OnClickListener() {           
        @Override
        public void onClick(View v) {                  
            if(passwordDialog == null) {
                passwordDialog = new Dialog(SettingsActivity.this); 
                passwordDialog.show(); 
            }
        }
    });