How to close Custom android.support.v7.app.AlertDialog.Builder?

Question

I have created a custom android.support.v7.app.AlertDialog.Builder and instead of using set positive and negative buttons I have designed a custom layout through xml (haveing ok and cancel buttons) and have assigned it to custom android.support.v7.app.AlertDialog.Builder.

I have set on click listeners on ok and cancel buttons. My problem is on click of cancel button I have set a callback to main fragment where I want to close/dismiss the dialog, but I am getting the following exception:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

how to fix this?

here is my code:

cancelbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
  Listener.OnCancel(); }});
@Override
public void OnCancel() {
final android.support.v7.app.AlertDialog dialog = custompopup.show();
dialog.cancel()}

Note that: Click listener on cancel button is in Custom class and OnCancel is in Main fragment, and custompopup is object of custom class and this object is initialized in a function that is a part of main fragment.


Show source
| android   | xml   | alertdialog   2017-01-04 06:01 3 Answers

Answers ( 3 )

  1. 2017-01-04 06:01

    Just check if the Dialog is already open or not. If it is open, then close it like this:

    Declare global:

    android.support.v7.app.AlertDialog dialog;
    

    Show dialog:

    dialog = custompopup.show();
    

    Dismiss Dialog in your listener like this:

    @Override
    public void OnCancel() {
      if (dialog.isShowing()) {
        dialog.dismiss();
      }
    }
    
  2. 2017-01-04 06:01

    final android.support.v7.app.AlertDialog dialog = custompopup.show();

    Before this line you need to dismiss your previous dialog. You can't create new one until you dismiss previous the previous one.

    Try this:

    dialog.dismiss();
    final android.support.v7.app.AlertDialog dialog = custompopup.show();
    

    your onCancel should look like this:

    @Override
    public void OnCancel() {
    dialog.cancel()
    if(dialog.isShowing(){
       dialog.dismiss();
      }
    android.support.v7.app.AlertDialog dialog = custompopup.show();
    }
    
  3. 2017-01-04 07:01

    You are getting exception because you are again showing the same dialog which is already shown. You are doing this thing in onCancel().

    You do not need to cancel/dismiss dialog in onCancel, its handled by system. onCancel will only call when dialog is cancelled by user, then its dismissed, no need to dismiss/cancel manually.

◀ Go back