关于AlertDialog的小坑
生活随笔
收集整理的這篇文章主要介紹了
关于AlertDialog的小坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當我們需要獲知AlertDialog是否正在顯示,我那個往我們會用到isShowing()方法,針對隱藏dialog的方法主要有三種:cancel()、hide()、dismiss()。但是不是調用這三個方法中的任意一個都能讓dialog .isShowing()返回false。
我們需要看一下源碼:
既然我們想調用isShowing()方法來判斷dialog是否正在顯示,那么我們就必須先看看這個方法的實現:
/*** @return Whether the dialog is currently showing.*/public boolean isShowing() {return mShowing;}
很簡單,就是返回了這么一個boolean型的變量,這個變量很明顯是用來標識dialog是否正在顯示的。
要想知道三個方法是否都能讓isShowing()方法返回false,那么我們就需要看看三個方法是怎樣影響mShowing這個變量的!
首先來看一下cancel方法的源碼:
/*** Cancel the dialog. This is essentially the same as calling {@link #dismiss()}, but it will* also call your {@link DialogInterface.OnCancelListener} (if registered).*/@Overridepublic void cancel() {if (!mCanceled && mCancelMessage != null) {mCanceled = true;// Obtain a new message so this dialog can be re-usedMessage.obtain(mCancelMessage).sendToTarget();}dismiss();}
可見最終調用了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}.*/@Overridepublic void dismiss() {if (Looper.myLooper() == mHandler.getLooper()) {dismissDialog();} else {mHandler.post(mDismissAction);}}
dismiss方法調用了dismissDialog(),那我們還得去看看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()兩個方法都給mShowing變量賦值為false了。
那么,hide()方法呢?來看一下源碼:
/*** Hide the dialog, but do not dismiss it.*/public void hide() {if (mDecor != null) {mDecor.setVisibility(View.GONE);}}
hide()方法沒有調用任何其他的方法,就這么短短三行,只是把dialog設置成了GONE。。因此,hide()方法并沒有改變mShowing的值。
看到這里我們就知道為什么我說三個方法不是都能讓isShowing方法返回準確的值了。
所以,如果你需要用isShowing方法判斷dialog是否正在顯示,記得在隱藏dialog的時候不要使用hide方法。
總結
以上是生活随笔為你收集整理的关于AlertDialog的小坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 病毒种类
- 下一篇: 跟我学系列,走进Scrapy爬虫(六)S