Michael Yaworski
Michael Yaworski

Reputation: 13483

How can I tell when my Android alert dialog is cancelled?

Here is my alert:

new AlertDialog.Builder(Activity.this)
    .setMessage("You have unsaved text. Are you sure you want to leave?")
    .setCancelable(true)
    .setNegativeButton("Leave", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        {
            finish();
        }
    })
    .setPositiveButton("Stay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    }).show();

Notice how I allow the alert to be cancelable: .setCancelable(true)

How can I run some code once the alert is cancelled by the user pressing the back button?

Upvotes: 0

Views: 903

Answers (1)

Michael Yaworski
Michael Yaworski

Reputation: 13483

According to the AlertDialog.Builder documentation on Android's website, you can use the setOnCancelListener (DialogInterface.OnCancelListener onCancelListener) method to handle when the dialog is cancelled.

.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) 
    {
        // do what you need when the dialog is cancelled
    }
})

So, your code would change to this:

new AlertDialog.Builder(Activity.this)
    .setMessage("You have unsaved text. Are you sure you want to leave?")
    .setCancelable(true)
    .setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) 
        {
            // do what you need when the dialog is cancelled
        }
    })
    .setNegativeButton("Leave", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        {
            finish();
        }
    })
    .setPositiveButton("Stay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    }).show();

Upvotes: 3

Related Questions