// 一个自定义的布局,作为显示的内容
Context context = null; // 真实环境中要赋值
int layoutId = 0; // 布局ID
View contentView = LayoutInflater.from(context).inflate(layoutId, null);
final PopupWindow popupWindow = new PopupWindow(contentView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
// 这里单独写一篇文章来分析
popupWindow.setBackgroundDrawable(new ColorDrawable());
// 设置好参数之后再show
popupWindow.showAsDropDown(contentView);
/**
* 计算出来的位置,y方向就在anchorView的上面和下面对齐显示,x方向就是与屏幕右边对齐显示
* 如果anchorView的位置有变化,就可以适当自己额外加入偏移来修正
* @param anchorView 呼出window的view
* @param contentView window的内容布局
* @return window显示的左上角的xOff,yOff坐标
*/
private static int[] calculatePopWindowPos(final View anchorView, final View contentView) {
final int windowPos[] = new int[2];
final int anchorLoc[] = new int[2];
// 获取锚点View在屏幕上的左上角坐标位置
anchorView.getLocationOnScreen(anchorLoc);
final int anchorHeight = anchorView.getHeight();
// 获取屏幕的高宽
final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());
final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
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 windowPos;
}
View windowContentViewRoot = 我们要设置给PopupWindow进行显示的View int windowPos[] = calculatePopWindowPos(view, windowContentViewRoot); int xOff = 20;// 可以自己调整偏移 windowPos[0] -= xOff; popupwindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]); // windowContentViewRoot是根布局View
/**
* 获取屏幕高度(px)
*/
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* 获取屏幕宽度(px)
*/
public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有