美文网首页Android开发经验谈
PopupWindow 在Android 7.0后位置不正确,包

PopupWindow 在Android 7.0后位置不正确,包

作者: HarveyLegend | 来源:发表于2018-05-18 14:53 被阅读159次

这个问题大家可能都遇到过,网上也有解决方案,一般都是如下这种:

@Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);// 以屏幕 左上角 为参考系的
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;  //屏幕高度减去 anchor 的 bottom
            setHeight(h);// 重新设置PopupWindow高度
        }
        super.showAsDropDown(anchor);
    }

这种方法能够解决一部分场景下的问题:在Activity/Fragment中弹出PopupWindow,并且没有输入法干扰。

但是在项目中有两个场景这个方法不行,第一是Activity中弹出输入法,这个时候popupWindow的位置会向上移动;第二是在dialog中弹出popupWindow,位置很奇葩。解决方法如下:

Activity中
if (Build.VERSION.SDK_INT < 24) {
          popupWindow.showAsDropDown(anchor);
    } else {
         int[] location = new int[2];
         anchor.getLocationOnScreen(location);
         int y = location[1];
         popupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, y + anchor.getHeight());
  }
Dialog中
if (Build.VERSION.SDK_INT < 24) {
          popupWindow.showAsDropDown(anchor);
    } else {
         int[] location = new int[2];
         anchor.getLocationInWindow(location);
         int y = location[1];
         popupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, y + anchor.getHeight());
  }
我们都知道showAtLocation第一个参数实际并不充当anchor的作用,如果Gravity设置为NO_GRAVITY,第二三个参数偏移量的参照点是左上角,Activity中是屏幕左上角,而Dialog中是Window窗口的左上角。

以上测试基于Android8.1的Nubia系统。

相关文章

网友评论

    本文标题:PopupWindow 在Android 7.0后位置不正确,包

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