详解Android PopupWindow怎么合理控制弹出位置(showAtLocation)

  

说到PopupWindow,应该都会有种熟悉的感觉,使用起来也很简单

     //一个自定义的布局,作为显示的内容   上下文语境=零;//真实环境中要赋值   int layoutId=0;//布局ID   视图contentView=LayoutInflater.from(上下文).inflate (layoutId, null);      最后PopupWindow PopupWindow=new PopupWindow (contentView   LayoutParams。WRAP_CONTENT LayoutParams。WRAP_CONTENT,真正的);      popupWindow.setTouchable(真正的);//如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是返回键都无法把弹框//这里单独写一篇文章来分析   popupWindow。setBackgroundDrawable(新ColorDrawable ());//设置好参数之后再显示   popupWindow.showAsDropDown (contentView);   之前      

如果创建PopupWindow的时候没有指定高宽,那么showAsDropDown默认只会向下弹出显示,这种情况有个最明显的缺点就是:弹窗口可能被屏幕截断,显示不全,所以需要使用到另外一个方法showAtLocation,这个的坐标是相对于整个屏幕的,所以需要我们自己计算位置。

  

如下图所示,我们可以根据屏幕左上角的坐标,屏幕高宽,点击视图的左上角的坐标C点击视图的大小以及PopupWindow布局的大小计算出PopupWindow的显示位置B

  

, 详解Android PopupWindow怎么合理控制弹出位置(showAtLocation)

  

计算方法源码如下:

     /* *   *计算出来的位置,y方向就在anchorView的上面和下面对齐显示,x方向就是与屏幕右边对齐显示   *如果anchorView的位置有变化,就可以适当自己额外加入偏移来修正   * @param anchorView呼出窗口的视图   * @param contentView窗口的内容布的局   * @return窗口显示的左上角的发送葡开,yOff坐标   */私有静态int [] calculatePopWindowPos (anchorView最终视图,最后视图contentView) {   最后一个int windowPos []=new int [2];   最后一个int anchorLoc []=new int [2];//获取锚点视图在屏幕上的左上角坐标位置   anchorView.getLocationOnScreen (anchorLoc);   最后一个int anchorHeight=anchorView.getHeight ();//获取屏幕的高宽   最后一个int screenHeight=ScreenUtils.getScreenHeight (anchorView.getContext ());   最后一个int screenWidth=ScreenUtils.getScreenWidth (anchorView.getContext ());   contentView.measure (View.MeasureSpec。不明,View.MeasureSpec.UNSPECIFIED);//计算contentView的高宽   最后一个int windowHeight=contentView.getMeasuredHeight ();   最后一个int windowWidth=contentView.getMeasuredWidth ();//判断需要向上弹出还是向下弹出显示   最后布尔isNeedShowUp=(screenHeight - anchorLoc [1]——anchorHeight & lt;windowHeight);   如果(isNeedShowUp) {   windowPos [0]=screenWidth - windowWidth;   windowPos [1]=anchorLoc [1]——windowHeight;   其他}{   windowPos [0]=screenWidth - windowWidth;   windowPos [1]=anchorLoc [1] + anchorHeight;   }   返回windowPos;   }      之前      

接下来调用showAtLoaction显示:

        视图windowContentViewRoot=我们要设置给PopupWindow进行显示的观点   int windowPos []=calculatePopWindowPos(视图,windowContentViewRoot);   int发送葡开=20;//可以自己调整偏移   windowPos[0] -=发送葡开;   popupwindow。showAtLocation(视图中,重力。|重力。首先,windowPos [0], windowPos [1]);//windowContentViewRoot是根布局查看      

上面的例子只是提供了一种计算方式,在实际开发中可以根据需求自己计算,比如anchorView在左边的情况,在中间的情况,可以根据实际需求写一个弹出位置能够自适应的PopupWindow。

  

补充上获取屏幕高宽的代码ScreenUtils.java:

     /* *   *获取屏幕高度(像素)   */公共静态int getScreenHeight(上下文语境){   返回context.getResources () .getDisplayMetrics () .heightPixels;   }/* *   *获取屏幕宽度(像素)   */公共静态int getScreenWidth(上下文语境){   返回context.getResources () .getDisplayMetrics () .widthPixels;   }      

演示截图展示:

  

详解Android PopupWindow怎么合理控制弹出位置(showAtLocation)

  

详解Android PopupWindow怎么合理控制弹出位置(showAtLocation)

  

详解Android PopupWindow怎么合理控制弹出位置(showAtLocation)