- 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(); }
- 在生成popupWindow的父Activity销毁之前,需要销毁popupWindow。否则会报内存泄露(leak)。也即在Activity的onDestroy()执行如下代码:
if (mPopupWindow != null) { mPopupWindow.dismiss(); mPopupWindow = null; }
- 在<=2.3的系统上,慎用setFocusable(boolean),一般设为mPopPm.setFocusable(false)
本文转自Kai的世界,道法自然博客园博客,原文链接:http://www.cnblogs.com/kaima/p/3160897.html,如需转载请自行联系原作者。