使用PopupWindow 的过程中设置高度无效

出现问题的原因

项目开发过程中避免不了使用PopupWindow控件,在使用的过程中设置 的height 使用 match_parentfill_parent导致的问题情况大致如下。

问题描述

api >=24(Android 7.0)时 View anchor 相对于anchor popupwindow 的位置 无效果 效果是全屏

    public void showAsDropDown(View anchor)
    public void showAsDropDown(View anchor, int xoff, int yoff)
    public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)  
    public void showAtLocation(View parent, int gravity, int x, int y)

代码如下:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.showAsDropDown(button);
            }
        });

效果如下

解决方法(网上有很多方法)

  if (Build.VERSION.SDK_INT < 24){
                    popupWindow.showAsDropDown(button);
   } else  {  // 适配 android 7.0
      int[] location = new int[2];
      button.getLocationOnScreen(location);
      int x = location[0];
      int y = location[1];
     popupWindow.showAtLocation(button, Gravity.NO_GRAVITY, x,y+button.getHeight());
 }

以上代码解决全屏问题

我擦 android 7.0 问题解决了,google android 7.1 出来了 MB 问题又来了

最后解决办法也是在多个版本修改之后的办法,结合了网上很多方案进行使用。

   if (Build.VERSION.SDK_INT < 24) {
                    popupWindow.showAsDropDown(button);
   } else {
        int[] location = new int[2];  // 获取控件在屏幕的位置
        button.getLocationOnScreen(location);
      if (Build.VERSION.SDK_INT == 25) {
         int tempheight = popupWindow.getHeight();
      if (tempheight == WindowManager.LayoutParams.MATCH_PARENT || screenHeight <= tempheight) {
             popupWindow.setHeight(screenHeight - location[1] - button.getHeight());
           }
     }
       popupWindow.showAtLocation(button, Gravity.NO_GRAVITY, location[0], location[1] + button.getHeight());
 }

猜你喜欢

转载自blog.csdn.net/u010551217/article/details/81203378