在這次做項目篩選功能時需要用到PopupWindow拦焚,但是在做的過程中發(fā)現(xiàn)一個問題偎蘸,如果要讓POP顯示在指定view正下方時帚称,調(diào)用showAsDropDown()這個方法嘹叫,而去pop窗口高度是match_parent嫩絮,在7.0以下系統(tǒng)顯示正常丛肢,但是在7.1顯示就不正常,不是自己想要的效果剿干。
popupWindow設(shè)置了居中或者底部對齊蜂怎,但是在7.0機器是跑到頂部。
很明顯這個bug是和我們設(shè)置了Gravity有關(guān)置尔。
展示popupWindow的函數(shù)有兩個杠步,showAtLocation 和 update。
重點看了那兩個函數(shù)的API 24 和 API 23 的區(qū)別榜轿。
解決方案一
我在24版本使用showAtLocation(View parent, int gravity, int x, int y)幽歼。其中parent只要為當(dāng)前頁面的view即可,gravity用Gravity.NO_GRAVITY差导,x,y為你要顯示的位置试躏。如果要顯示在某個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);
}
}