问题描述
当PopupWindow的高度设置为MATCH_PARENT时,showAsDropDown的位置会失效
解决方法
发现问题之后,上网搜了很多解决方案,发现都不能完美解决问题,如以下代码:
方法1.
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);
}
方法2.
public static void showAsDropDown(final PopupWindow pw, final View anchor, final int xoff, final int yoff) {
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);
}
}
这两种代码如果在含有虚拟按键或者全面屏手机下会存在兼容问题,显示的位置还是错误的
于是就产生了下面的方法
在你的PopupWindow的布局文件底部加一个LinearLayout占位 ,然后高度设置多一点,我这里设置了1000dp
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#50000000"
android:orientation="vertical">
<ListView
android:id="@+id/lv_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
android:background="@color/white"
android:listSelector="@color/transparent"
android:scrollbars="none"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="#50000000"/>
</LinearLayout>
然后将PopupWindow的高度设置为WRAP_CONTENT, 部分代码如下
setWidth(LayoutParams.MATCH_PARENT);
setHeight(LayoutParams.WRAP_CONTENT);
setContentView(contentView);
setFocusable(true);
setOutsideTouchable(true);
setBackgroundDrawable(new BitmapDrawable());
然后正常调用即可 showAsDropDown(view, 0, 0);
效果图: