【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)
posted @ 2013-06-28 15:05  Kai.Ma  阅读(7369)  评论(0编辑  收藏  举报