Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!
like image 704
Lerk Avatar asked Oct 23 '25 18:10

Lerk


2 Answers

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!");
                })
like image 133
Janus Varmarken Avatar answered Oct 26 '25 08:10

Janus Varmarken


You don't need to call dismiss or cancel inside setPositiveButton/setNegativeButton callback, so you can directly implement your logic there.

like image 26
Phuchit S. Avatar answered Oct 26 '25 06:10

Phuchit S.