/**
?* Cancel the dialog. ?This is essentially the same as calling {@link #dismiss()}, but it will
?* also call your {@link DialogInterface.OnCancelListener} (if registered).
?*/
public void cancel() {
if (!mCanceled && mCancelMessage != null) {
mCanceled = true;
// Obtain a new message so this dialog can be re-used
Message.obtain(mCancelMessage).sendToTarget();
}
dismiss();
}
然後我們再看dismiss源碼:
/**
* Dismiss this dialog, removing it 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 {@link #onStop}.
*/
@Override
public void dismiss() {
if (Looper.myLooper() == mHandler.getLooper()) {
dismissDialog();
} else {
mHandler.post(mDismissAction);
}
}
最後是dismissDialog方法:
void dismissDialog() {
if (mDecor == null || !mShowing) {
return;
}
if (mWindow.isDestroyed()) {
Log.e(TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!");
return;
}
try {
mWindowManager.removeViewImmediate(mDecor);
} finally {
if (mActionMode != null) {
mActionMode.finish();
}
mDecor = null;
mWindow.closeAllPanels();
onStop();
mShowing = false;
sendDismissMessage();
}
}
總結:從以上源碼可以看出,cancel方法其實就是調用的dismiss方法。只是如果設置了DialogInterface.OnCancelListener監聽,那麽使用cancel的話就可以監聽關閉的事件了。