关于AlertDialog的小坑
生活随笔
收集整理的這篇文章主要介紹了
关于AlertDialog的小坑
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
當(dāng)我們需要獲知AlertDialog是否正在顯示,我那個(gè)往我們會(huì)用到isShowing()方法,針對(duì)隱藏dialog的方法主要有三種:cancel()、hide()、dismiss()。但是不是調(diào)用這三個(gè)方法中的任意一個(gè)都能讓dialog .isShowing()返回false。
我們需要看一下源碼:
既然我們想調(diào)用isShowing()方法來判斷dialog是否正在顯示,那么我們就必須先看看這個(gè)方法的實(shí)現(xiàn):
/*** @return Whether the dialog is currently showing.*/public boolean isShowing() {return mShowing;}
很簡(jiǎn)單,就是返回了這么一個(gè)boolean型的變量,這個(gè)變量很明顯是用來標(biāo)識(shí)dialog是否正在顯示的。
要想知道三個(gè)方法是否都能讓isShowing()方法返回false,那么我們就需要看看三個(gè)方法是怎樣影響mShowing這個(gè)變量的!
首先來看一下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();}
可見最終調(diào)用了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方法調(diào)用了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()兩個(gè)方法都給mShowing變量賦值為false了。
那么,hide()方法呢?來看一下源碼:
/*** Hide the dialog, but do not dismiss it.*/public void hide() {if (mDecor != null) {mDecor.setVisibility(View.GONE);}}
hide()方法沒有調(diào)用任何其他的方法,就這么短短三行,只是把dialog設(shè)置成了GONE。。因此,hide()方法并沒有改變mShowing的值。
看到這里我們就知道為什么我說三個(gè)方法不是都能讓isShowing方法返回準(zhǔn)確的值了。
所以,如果你需要用isShowing方法判斷dialog是否正在顯示,記得在隱藏dialog的時(shí)候不要使用hide方法。
總結(jié)
以上是生活随笔為你收集整理的关于AlertDialog的小坑的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 病毒种类
- 下一篇: 跟我学系列,走进Scrapy爬虫(六)S