dialog中hide、dismiss、cancel方法的區別
阿新 • • 發佈:2019-01-09
主要我之前用的時候不知道dismiss和cancel有啥區別。。。然後今天想起來了就去查了一下,順便記下來備忘。
dismiss:大概就是刪除檢視,呼叫Onstop回撥,並把mShowing置為false。
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,只不過先判斷了mCancelMessage是否為空
@Override
public void cancel() {
if (!mCanceled && mCancelMessage != null) {
mCanceled = true;
Message.obtain(mCancelMessage).sendToTarget();
}
dismiss();
}
mCancelMessage實際上是把listener封裝成obj的Message
public void setOnCancelListener(@Nullable OnCancelListener listener) { if (mCancelAndDismissTaken != null) { throw new IllegalStateException( "OnCancelListener is already taken by " + mCancelAndDismissTaken + " and can not be replaced."); } if (listener != null) { mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener); } else { mCancelMessage = null; } }
hide:這是幹嘛的。。。隱藏起來又不銷燬,有啥用?萬一後面忘了呢,銷燬Activity的時候就會報錯:android.view.WindowLeaked: Activity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorViewthat was originally added here,所以建議不用。
public void hide() {
if (mDecor != null) {
mDecor.setVisibility(View.GONE);
}
}
總結:
建議用dismiss,這個比cancel少一個判斷,一般來說是夠用了,當然如果你有CancelListener的話就用cancel。。。