1.首先自定义PopupWindow
popWindowView= LinearLayout.inflate(context, R.layout.popupWindow,null);
popupWindow = new PopupWindow(popWindowView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
popupWindow.setOutsideTouchable(true);//点击弹窗以外的地方消失
popupWindow.setBackgroundDrawable(new BitmapDrawable());//响应返回键
2.一般我们会让弹出框在我们指定控件的某个位置展示,那么就有如下计算
/**
* @param anchorView 弹窗时作为参照物的view * @param contentView 内容布局(可以直接放popupWindow) * @return 左上角的x,y坐标 */ private static int[] PopViewPos(final View anchorView, final View contentView) { final int windowPos[] = new int[2]; final int anchorLoc[] = new int[2]; // 获取锚点View在屏幕上的左上角坐标位置,赋值给anchorLoc数组 anchorView.getLocationOnScreen(anchorLoc);
//获取参照view的高度 final int anchorHeight = anchorView.getHeight(); // 获取屏幕的高宽 final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext()); final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
//设置测量模式,让父容器不影响view的测量 contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); // 计算contentView的高宽 final int windowHeight = contentView.getMeasuredHeight(); final int windowWidth = contentView.getMeasuredWidth(); // 判断需要向上弹出还是向下弹出显示 final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight); if (isNeedShowUp) { windowPos[0] = screenWidth - windowWidth; windowPos[1] = anchorLoc[1] - windowHeight; } else { windowPos[0] = screenWidth - windowWidth; windowPos[1] = anchorLoc[1] + anchorHeight; } return viewPos; }
3.显示showAtLoaction
int viewPos[] = calculatePopWindowPos(view, contentView);
popupwindow.showAtLocation(view, Gravity.TOP | Gravity.START, viewPos[0], viewPos[1]);
/**
* 获取屏幕高度(px)
*/
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* 获取屏幕宽度(px)
*/
public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}