在這次項目需要用到PopupWindow,但發現如果你用showAsDropDown()這個方法,讓pop顯示在某個View的下面,而且pop的高度是match_parent的話,其顯示的位置在Android7.0以下系統正常,在7.0和7.1系統顯示不正常,點擊“打開POP”按鈕效果對比如下:
error.png
normal.png
相信大家都已經看到問題所在了吧,我希望在點擊篩選的時候,讓他顯示在篩選的下面,結果他把整個窗體都給覆蓋了。
原因分析請參考如下文章,目前估計是Google的問題,好像在7.1已經修復了
PopupWindow 在 Android N(7.0) 的兼容性問題
解決方案一
我在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);
}
}