Android對話框之dismiss和cancel和hide區別

在咱們看來二者效果都是同樣的,其實看下源碼就知道cancel確定會去調dismiss的,若是調用的cancel的話就能夠監聽DialogInterface.OnCancelListener。android

/**
     * 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。ide

/**
     * 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裏調用了onStopoop

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銷燬的時候就會出現崩潰日誌了,由於post

Activity銷燬時是須要把對話框都關閉掉的。this

日誌以下:spa

android.view.WindowLeaked: Activity com.example.androidtest_progressdialog.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{434557e8 G.E..... R.....ID 0,0-1026,288} that was originally added here線程

再看一下hide裏是作什麼操做:日誌

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

能夠看出,hide只是把對話框裏的DecorView設置爲不可見,並無從Window移除掉這個DecorView。code

相關文章
相關標籤/搜索