PopupWindow的显示位置

前段时间在使用PopupWindow时,对PopupWindow的显示位置有一些疑惑,今天整理整理。

首先看看PopupWindow显示的效果:

popupwindow.gif

可以从动图中看到PopupWindow分别出现在了按钮的左侧、按钮中间和按钮右对齐的位置。

使用showAsDropDown(View anchor, int xoff, int yoff)方法就可以满足这三个位置的显示需求。

Left PopupWindow

首先显示在按钮下方左侧的PopupWindow很好理解,就是showAsDropDown()的默认显示效果,直接调用showAsDropDown(button,0,0);就ok。

重点说说显示在中间的PopupWindow和右对齐显示的PopupWindow。

在说之前先看一张图:

popupwindow 2 2.jpeg

在showAsDropDown()方法中,对应的坐标轴如上图。原点在按钮下方左侧,往右是X轴正方向,往下是Y轴正方向。

确定坐标轴后,就可以计算B和C位置的PopupWindow的偏移量了。为了图看起来更清晰,所以我把3个PopupWindow在Y轴上被画成了三级,实际上在Y轴是没有偏移的。

Middle PopupWindow

从图中可以计算出B位置在X轴的偏移量就是按钮宽度的一半再减去popupwindow宽度的一半。

代码如下:

        mPopupWindow1.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); //这句代码必须要才能获得正确的popupwindow的宽度
        int xOff;
        int buttonWidth = button3.getWidth();
        int popupwindowWidth = mPopupWindow1.getContentView().getMeasuredWidth();

        xOff = buttonWidth / 2 - popupwindowWidth / 2;
        mPopupWindow1.showAsDropDown(button3, xOff, 0);

不使用mPopupWindow1.getWidth()方法的原因是mPopupWindow1.getWidth()获得的值是-2,因为我在布局文件中设置PopupWindow的宽度是wrap_content,不能获取到正确的PopupWindow宽度,所以需要在手动使用measure()方法测量PopupWindow的宽高后,再使用getMeasuredWidth()方法来获取其宽度。

Right PopupWindow

Right PopupWindow也同理,从图中可以看出right popupWindow在X轴的偏移量为按钮宽度再减去PopupWindow的宽度。

代码如下:

        mPopupWindow1.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int xOff;
        int buttonWidth = button4.getWidth();
        int popupwindowWidth = mPopupWindow1.getContentView().getMeasuredWidth();

        xOff = buttonWidth - popupwindowWidth;
        mPopupWindow1.showAsDropDown(button4, xOff, 0);

底部的PopupWindow

底部的PopupWindow使用showAtLocation()显示。

mPopupWindow2.showAtLocation(view, Gravity.BOTTOM, 0, 0);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值