版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013963364/article/details/84788559
最近遇到一个bug,在一台Android4.4.4的手机上PopupWindow的位置突然跳动到屏幕的左上角,特地把解决过程记录下来。
这个是正常的情况异常的情况
复现条件:
1. 锚点View被remove,上图是被remove重新创建的View
2. 布局中有滑动控件,触发了滑动
3.api19的手机系统
分析:当按钮被remove后,PopupWindow还未取消时,当页面触发的了数据刷新,window位置被重置了。
API19的PopupWindow代码有注册滚动监听
API28的源码
对比可以看到高版本的源码判断了isAttachedToWindow(),这也解释了高版本的系统上PopupWindow未改变位置,而4.4.4上位置改变的现象。
解决方案:
//继承PopupWindow 用该方法将窗口显示在anchor控件下方
show(View anchor) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
int[] locaRoot = new int[2];
int[] loca = new int[2];
View root = anchor.getRootView();
root.getLocationInWindow(locaRoot);
anchor.getLocationInWindow(loca);
int x = (loca[0]-locaRoot[0]) + anchor.getWidth() / 2 - mPopMenuWidth;
int y = -(root.getHeight() - (loca[1] - locaRoot[1]) - anchor.getHeight());
showAsDropDown(root, x, y);
} else {
// x方向的偏移 居中显示
int xOffset = getXOffset(anchor);
showAsDropDown(anchor, xOffset, 0);
}
}
项目中是在锚点控件下方显示的PopupWindow,也可以根据实际需求调整计算的x,y