9

Curiosity question here.

I use a lot of dialogs builders and most of the time my negative cancel button do nothing except dismiss the dialog. The code I found everywhere on the web is this :

builder.setNegativeButton(
    "cancel",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    }
);

I happened to find out that this code do exactly the same :

builder.setNegativeButton("cancel", null);

So my question is then : is that a bad habit not to manually dismiss the dialog, and if yes why ?

Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92

2 Answers2

11

It is somewhat documented behaviour, see:
http://developer.android.com/guide/topics/ui/dialogs.html#DismissingADialog

When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.

So with null listener you exercise this implicit documented behaviour of Dialog.

What can go possibly wrong? (yeah, I think there's at least 50% chance that some custom ROM out there is not behaving properly... then again, who cares about custom ROMs failing to follow documented behavior, I don't any more, too much of that BS).

2

I learned this myself in an Android course in school. Basically, you only need to implement the button listener if you need additional functionality.

So it is not "habit" to include the click listener, it is just clear intent.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • That should be in the doc. Thanks for answer – Dan Chaltiel Jan 09 '16 at 22:35
  • 1
    If it's not in the documentation I wouldn't trust it. It can change without warning and your users will see crashing apps. – zmbq Jan 10 '16 at 07:34
  • @zmbq - why would a null check change in the Android API? If anything, they should add more, not remove any. The documentation states to put an instance of the listener for that parameter. It is implied if you don't want one to put null. – OneCricketeer Jan 10 '16 at 07:58
  • 1
    For reference, setting null also removes a click listener. Further demonstrating that null is not a problem. http://stackoverflow.com/a/5195379/2308683 – OneCricketeer Jan 10 '16 at 08:08