Android技术

PopupWindow显示位置错误(7.0)

2017-08-24  本文已影响26人  Pin_ZL

在这次做项目筛选功能时需要用到PopupWindow,但是在做的过程中发现一个问题,如果要让POP显示在指定view正下方时,调用showAsDropDown()这个方法,而去pop窗口高度是match_parent,在7.0以下系统显示正常,但是在7.1显示就不正常,不是自己想要的效果。

popupWindow设置了居中或者底部对齐,但是在7.0机器是跑到顶部。

很明显这个bug是和我们设置了Gravity有关。

展示popupWindow的函数有两个,showAtLocation 和 update。

重点看了那两个函数的API 24 和 API 23 的区别。

解决方案一

我在24版本使用showAtLocation(View parent, int gravity, int x, int y)。其中parent只要为当前页面的view即可,gravity用Gravity.NO_GRAVITY,x,y为你要显示的位置。如果要显示在某个view的下面,就获取该view的坐标就好。

if (Build.VERSION.SDK_INT >= 24) {

 //7.0以上系统

//获取目标控件在屏幕中的坐标位置

int[] location = new int[2];

anchor.getLocationOnScreen(location);

mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, location[1] );

} else {

mPopupWindow.showAsDropDown(anchor);

}

方法二

重写popWindows的showAsDropDown方法

public class CustomPopupWindowextends PopupWindow {

public CustomPopupWindow(Context context) {

super(context, null);

}

@Override

public void showAsDropDown(View anchor) {

if (Build.VERSION.SDK_INT >= 24) {

Rect rect = new Rect();

anchor.getGlobalVisibleRect(rect);

int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;

setHeight(h);

}

super.showAsDropDown(anchor);

}

}
上一篇下一篇

猜你喜欢

热点阅读