popupwindow位置显示问题

我们在开发中会用到popupwindow,当在一个列表中,每一个item都有一个点击事件,显示popupwindow的,当数据比较多时,我们向下弹出的popupwindow就可能被屏幕遮盖显示不出来。这个时候就需要我们来判断是向下弹出,还是向上弹出

View contentView = LayoutInflater.from(getActivity())
                                 .inflate(R.layout.online_delete_popup, null);
mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
mPopupWindow.setBackgroundDrawable(new ColorDrawable());
// 设置好参数之后再show
int windowPos[] = PopupWindowUtil.calculatePopWindowPos(view, contentView);
int xOff = 20; // 可以自己调整偏移
windowPos[0] -= xOff;
mPopupWindow.showAtLocation(view,
        Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);

用到的工具:

public class PopupWindowUtil {
    /**
     * 计算出来的位置,y方向就在anchorView的上面和下面对齐显示,x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化,就可以适当自己额外加入偏移来修正
     * @param anchorView  呼出windowview
     * @param contentView   window的内容布局
     * @return window显示的左上角的xOff,yOff坐标
     */
    public static int[] calculatePopWindowPos(final View anchorView, final View contentView) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());
        final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
        // 测量contentView
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
        } else {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }
}

猜你喜欢

转载自blog.csdn.net/gqdbk/article/details/80974661