【Android開發坑系列】之PopupWindow

  1. PopupWindow在4.0以前的版本有個系統級別的BUG,必須藉助一段自定義的fix代碼來修復。其中mPopPm就是PopupWindow實例。
    java.lang.NullPointerException
    at android.widget.PopupWindow$1.onScrollChanged

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                try {
                    final Field fAnchor = PopupWindow.class.getDeclaredField("mAnchor");
                    fAnchor.setAccessible(true);
                    Field listener = PopupWindow.class.getDeclaredField("mOnScrollChangedListener");
                    listener.setAccessible(true);
                    final ViewTreeObserver.OnScrollChangedListener originalListener = (ViewTreeObserver.OnScrollChangedListener) listener
                            .get(mPopPm);
                    ViewTreeObserver.OnScrollChangedListener newListener =
                            new ViewTreeObserver.OnScrollChangedListener() {
                                public void onScrollChanged() {
                                    try {
                                        View mAnchor = (View) fAnchor.get(mPopPm);
                                        if (mAnchor == null) {
                                            return;
                                        } else {
                                            originalListener.onScrollChanged();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            };
                    listener.set(mPopPm, newListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
  2. 在生成popupWindow的父Activity銷燬以前,須要銷燬popupWindow。不然會報內存泄露(leak)。也即在Activity的onDestroy()執行以下代碼:
            if (mPopupWindow != null) {
                mPopupWindow.dismiss();
                mPopupWindow = null;
            }
  3. 在<=2.3的系統上,慎用setFocusable(boolean),通常設爲mPopPm.setFocusable(false)
相關文章
相關標籤/搜索