您的位置:首页 > 移动开发 > Android开发

Android PopupWindow 的显示位置

2015-09-04 09:59 495 查看
本文在上一篇博客 Android PopupWindow 仿微信点赞和评论弹出框 中例子的基础上,探讨 showAsDropDown() 和 showAtLocation() 参数的作用。

1. Android 坐标系

Android 坐标系是以左上角为原点,水平向右是 x 轴,竖直向下是 y 轴。showAsDropDown() 中的坐标是相对于anchor的偏移值,而 showAtLocation() 中的坐标是相对于左上角原点的偏移值。

Android 坐标系如下图:



2. showAsDropDown()

showAsDropDown() 有2种形式:showAsDropDown(View anchor),showAsDropDown(View anchor, int xoff, int yoff)。其中前者是对 showAsDropDown(View anchor, 0, 0) 的重载,故我们只介绍后者即可。在上一篇博客的基础上,我们将说说的内容即 tvContent 来触发弹出框,即

[code]            tvContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showMore(v);
                }
            });


采用不同的参数,效果如下表所示:



showAsDropDown(tvContent, 0, 0)showAsDropDown(moreBtn, 0, 0)
从上图可以看出,showAsDropDown(View anchor, 0, 0) 默认是将PopupWindow 的左上角与 anchor 的左下角对齐的。当无法对齐时,右图即为此种情况,moreBtn 过于靠右,导致二者无法实现左侧线对齐,则 PopupWindow 右侧顶着屏幕右边缘放置。

3. showAtLocation()

showAtLocation(View parent, int gravity, int x, int y),此 parent 并不是我们通常理解的 parent,从这篇博文 Android开发PopupWindow showAtLocation用法 可知:

第一个参数是View类型的parent,虽然这里参数名是parent,其实,不是把PopupWindow放到这个parent里,并不要求这个parent是一个ViewGroup,这个参数名让人误解。官方文档”a parent view to get the android.view.View.getWindowToken() token from“,这个parent的作用应该是调用其getWindowToken()方法获取窗口的Token,所以,只要是该窗口上的控件就可以了。

各个参数对应的效果图如下表:

..


showAtLocation(tvContent, Gravity.TOP, 0, 0)showAtLocation(tvContent, Gravity.RIGHT, 0, 0)
..


showAtLocation(tvContent, Gravity.BOTTOM, 0, 0)showAtLocation(tvContent, Gravity.LEFT, 0, 0)
..


showAtLocation(tvContent, Gravity.CENTER, 0, 0)showAtLocation(tvContent, Gravity.LEFT | Gravity.TOP, 0, 0)
..

showAtLocation(tvContent, Gravity.NO_GR***ITY, 0, 0)

4. 类似博文

http://orgcent.com/android-popupwindow-showasdropdown-showatlocation/

http://blog.csdn.net/dxj007/article/details/8026691

http://www.pocketdigi.com/20130218/987.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: