[转]Android对话框中dismiss和cancel、hide的区别

/ 0评 / 1

dismiss和cancel在我们看来两者效果都是一样的,其实看下源码就知道cancel肯定会去调dismiss的,不过如果我们调用的cancel的话就可以监听DialogInterface.OnCancelListener,不调用cancel的话就只能监听DialogInterface.OnDismissListener。

/**
 * 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方法,实在需要就在onStop里去override。

/**
 * 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里调用了onStop。

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();
    }
}

hide方法,注释上说了hide只是隐藏了对话框并没有销毁,如果打算用这方法来销毁对话框就会出现问题,在Activity销毁的时候就会出现崩溃日志了,因为Activity销毁时是需要把对话框都关闭掉的。不然会报窗口泄露异常

/**
 * Hide the dialog, but do not dismiss it.
 */
public void hide() {
    if (mDecor != null) {
        mDecor.setVisibility(View.GONE);
    }
}

原文链接 : bvin的博客

发表评论

您的电子邮箱地址不会被公开。