Search code examples
javaandroidandroid-alertdialogevent-listener

Android onDismissListener called on Cancel


I added an AlertDialog.OnDismissListener to my AlertDialog. When dialog.cancel() is invoked, the onCancelListener as well as the onDismissListener is called.

Is this expected behavior? Can I somehow prevent the onDismissListener from being called when dialog.cancel() is called instead of dialog.dismiss()?

Have some code:

AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setView(view)
                .setTitle(title)
                .setIcon(icon)
                .setCancelable(true)
                .setNegativeButton(R.string.cancel, (d, i) -> {
                    d.cancel();
                    Log.d(TAG, "Cancel pressed!");
                })
                .setPositiveButton(positiveBtnText, (d, i) -> {
                    d.dismiss();
                    Log.d(TAG, "Dismiss pressed!");
                });
        AlertDialog dialog = builder.create();
        dialog.setOnCancelListener(dialogInterface -> {
            Log.d(TAG, "Dialog canceled!");
        });
        dialog.setOnDismissListener(dialogInterface -> {
            Log.d(TAG, "Dialog dismissed!");
        });

The unexpected behavior also appears in the log:

03-25 05:15:31.895 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Cancel pressed!
03-25 05:15:31.895 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Operation canceled!
03-25 05:15:31.896 25985-25985/io.l.l D/io.l.l.u.ArrayAdapter: Dismiss called!

Solution

  • There is no reason to use both the setNegativeButton/setPositiveButton and setting OnCancelListener/OnDismissListener.

    Remove:

    dialog.setOnCancelListener(dialogInterface -> {
                Log.d(TAG, "Dialog canceled!");
            });
            dialog.setOnDismissListener(dialogInterface -> {
                Log.d(TAG, "Dialog dismissed!");
            });
    

    And add the code that you want to run when the user presses OK inside the listener that you supply to setPositiveButton:

    // ...
    .setPositiveButton(positiveBtnText, (d, i) -> {
                        // Your code that reacts to the user pressing "OK" goes here!
                        Log.d(TAG, "OK pressed!");
                    });
    

    And similarly add the code that you want to run when the user presses Cancel inside the listener that you supply to setNegativeButton:

    .setNegativeButton(R.string.cancel, (d, i) -> {
                        // Your code that reacts to the user pressing "Cancel" goes here!
                        Log.d(TAG, "Cancel pressed!");
                    })