项目中使用PopupWindown出现的坑
1、部分设备,PopWindow在Android4.0后版本,出现NullPointerException调用以下方法可解决, fixPopupWindow(p)在实例化后调用
/**
* 在new PopupWindow()后调用 兼容4.0(ICE_CREAM_SANDWICH)以下版本 <br>
* 防止错误<br>
* java.lang.NullPointerException<br>
* at android.widget.PopupWindow$1.onScrollChanged(PopupWindow.java:
*
* @param window
*/
public static void fixPopupWindow(final PopupWindow window) {
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(window);
ViewTreeObserver.OnScrollChangedListener newListener = new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
try {
@SuppressWarnings("unchecked")
WeakReference<View> mAnchor = (WeakReference<View>) fAnchor
.get(window);
if (mAnchor == null || mAnchor.get() == null) {
return;
} else {
originalListener.onScrollChanged();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
};
listener.set(window, newListener);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、在想要实现点击返回键后popupWindow自动消失时,返现popupWindow为null。请为popupWindow设置一个背景
popWindow.setFocusable(true);
popWindow.setBackgroundDrawable(new PaintDrawable(0x88000000));
popWindow.setOutsideTouchable(true);