本文转自 http://www.lai18.com/content/1053890.html
showAsDropDown() 中的坐标是相对于anchor的偏移值,而 showAtLocation() 中的坐标是相对于左上角原点的偏移值。
1. Android 坐标系
Android 坐标系是以左上角为原点,水平向右是 x 轴,竖直向下是 y 轴。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) |
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_GRAVITY, 0, 0) |