PopupWindow计算弹出位置

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;
    }
 

转载于:https://www.cnblogs.com/mrzha/p/8398486.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值