在這次做項(xiàng)目篩選功能時(shí)需要用到PopupWindow,但是在做的過程中發(fā)現(xiàn)一個(gè)問題,如果要讓POP顯示在指定view正下方時(shí),調(diào)用showAsDropDown()這個(gè)方法,而去pop窗口高度是match_parent,在7.0以下系統(tǒng)顯示正常,但是在7.1顯示就不正常,不是自己想要的效果。
popupWindow設(shè)置了居中或者底部對(duì)齊,但是在7.0機(jī)器是跑到頂部。
很明顯這個(gè)bug是和我們?cè)O(shè)置了Gravity有關(guān)。
展示popupWindow的函數(shù)有兩個(gè),showAtLocation 和 update。
重點(diǎn)看了那兩個(gè)函數(shù)的API 24 和 API 23 的區(qū)別。
解決方案一
我在24版本使用showAtLocation(View parent, int gravity, int x, int y)。其中parent只要為當(dāng)前頁(yè)面的view即可,gravity用Gravity.NO_GRAVITY,x,y為你要顯示的位置。如果要顯示在某個(gè)view的下面,就獲取該view的坐標(biāo)就好。
if (Build.VERSION.SDK_INT >= 24) {
//7.0以上系統(tǒng)
//獲取目標(biāo)控件在屏幕中的坐標(biāo)位置
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);
}
}