美文网首页安卓UI
PopupWindow的显示位置

PopupWindow的显示位置

作者: 程序员张晴天 | 来源:发表于2018-12-30 13:57 被阅读131次

    前段时间在使用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);
    

    相关文章

      网友评论

        本文标题:PopupWindow的显示位置

        本文链接:https://www.haomeiwen.com/subject/fiuplqtx.html