原本据说这事sdk24 25 带的一个bug 但是延伸到了 8.0就有点奇怪了
网上搜到的方法大部分是
if (Build.VERSION.SDK_INT >= 24) { int[] location = new int[2]; anchor.getLocationOnScreen(location); // 7.1 版本处理 if (Build.VERSION.SDK_INT == 25) { WindowManager windowManager = (WindowManager) pw.getContentView().getContext().getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) { int screenHeight = windowManager.getDefaultDisplay().getHeight(); // PopupWindow height for match_parent, will occupy the entire screen, it needs to do special treatment in Android 7.1 pw.setHeight(screenHeight - location[1] - anchor.getHeight() - yoff); } } pw.showAtLocation(anchor, Gravity.NO_GRAVITY, xoff, location[1] + anchor.getHeight() + yoff); } else { pw.showAsDropDown(anchor, xoff, yoff); }
简单来说就是 通过测量view在window的位置 然后测定偏移量 然后显示出来 但是测量后 你会发现在 Android 8.0手机上 会无效
但是思路可以借鉴啊
于是有人研究出第二种方法 既然测量windows位置不准确 那就直接测量view在屏幕上的像素位置 然后运算得出相应的需要显示位置
if (Build.VERSION.SDK_INT >= 24) { Rect visibleFrame = new Rect(); anchor.getGlobalVisibleRect(visibleFrame); int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom; pw.setHeight(height); pw.showAsDropDown(anchor, xoff, yoff); } else { pw.showAsDropDown(anchor, xoff, yoff); }
亲测有效
原文地址点击打开链接