Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

PopupWindow 不響應 Back 鍵的原理與解法

編輯:關於 Android 程式設計

在 PopupWindow 的原始碼中,preparePopup 方法有一個關鍵判斷:

 private void preparePopup(WindowManager.LayoutParams p) { if (mContentView == null || mContext == null || mWindowManager == null) { throw new IllegalStateException("You must specify a valid content view by calling setContentView() before attempting to show the popup."); } if (mBackground != null) { final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams(); int height = ViewGroup.LayoutParams.MATCH_PARENT; if (layoutParams != null && layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) { height = ViewGroup.LayoutParams.WRAP_CONTENT; } // 當有背景可用時,將 content view 嵌入另一個擁有背景 drawable 的 view PopupViewContainer popupViewContainer = new PopupViewContainer(mContext); PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height); popupViewContainer.setBackgroundDrawable(mBackground); popupViewContainer.addView(mContentView, listParams); mPopupView = popupViewContainer; } else { mPopupView = mContentView; } mPopupWidth = p.width; mPopupHeight = p.height; }

從原始碼可以看到:只有在背景(mBackground)不為空時,才會建立 PopupViewContainer。而 PopupWindow 正是透過 PopupViewContainer 這個內部類別來回應按鍵的。

PanelsViewContainer 的 dispatchKeyEvent 方法處理了 Back 鍵的邏輯:

 private class PopupViewContainer extends FrameLayout { @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (getKeyDispatcherState() == null) { return super.dispatchKeyEvent(event); } if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null && state.isTracking(event) && !event.isCanceled()) { dismiss(); return true; } } return super.dispatchKeyEvent(event); } else { return super.dispatchKeyEvent(event); } } }

當按下 Back 鍵並在放開時,若條件都滿足,便會呼叫 dismiss() 關閉 PopupWindow。然而,這個回應 Back 鍵的能力完全依賴於 PopupViewContainer 的存在,而它只有在背景不為空時才會被建立。

結論:若想讓 PopupWindow 不響應 Back 鍵,只需將它的 background 設定為 null 即可。此時 mPopupView 會直接等於 mContentView,不會建立 PopupViewContainer,Back 鍵自然也就不會觸發 dismiss()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved