What is the difference between a dialog being dismissed or canceled in Android?
Like the title says, what is the difference between a dialog being dismissed or canceled in Android?
Typically, a dialog is dismissed when its job is finished and it is being removed from the screen. A dialog is canceled when the user wants to escape the dialog and presses the Back button.
For example, you have a standard Yes/No dialog on the screen. If the user clicks No, then the dialog is dismissed and the value for No is returned to the caller. If instead of choosing Yes or No, the user clicks Back to escape the dialog rather than make a choice then the dialog is canceled and no value is returned to the caller.
dismiss
is something you have to explicitly call in your code, usually to respond to a click event on a button in your Dialog
. If you prefer, you can call dismissDialog
in the Activity
, which will in turn call dismiss
on the Dialog
.
The cancel
method only executes when it is explicitly called in your code, or when the user presses the BACK button when your cancelable Dialog
is open (as @Lee noted).
If you are using a DatePicker
, then all of this is still the case. As @Lee said, DatePickerDialog.OnDateSetListener
just detects when the user has chosen a date from the DatePicker
.
The Android Developer Reference provides more info on Dialog
s.
Dismiss
Calling the dismiss removes the dialog from the screen. This method can be
invoked safely from any thread. Note that you should not override this method to do cleanup when the dialog is dismissed, instead implement that in onStop.
Cancel
Calling the cancel, cancels the dialog. This is essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener, if registered.
Hide
This method hides the dialog, but do not dismiss it.
And for more see here
The difference is all about returning the value to the caller function.
dialog.cancel()
will normally be called when the user hits the back button rather than selecting the choices that alert dialog offers like OK/Dismiss and return null/no value to the caller. While
dialog.dismiss()
is normally called when the user selects from the choices that alert dialog offers like hitting the Dismiss button on the dialog will dismiss the dialog and will return the non-null corresponding value to the caller. That's it.