在這次做項目篩選功能時需要用到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);
}
}