美文网首页Android开发经验谈Android-ui效果
Android PopupWindow 实现自动计算弹出位置

Android PopupWindow 实现自动计算弹出位置

作者: songdehuai | 来源:发表于2018-05-02 13:52 被阅读38次

android中PopupWindow弹出位置实现自动计算,并且跟随在控件下方

    /**
     * 计算出来的位置,y方向就在anchorView的上面和下面对齐显示,x方向就是与View的中心点对齐
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private int[] calculatePopWindowPos(final View anchorView, final View contentView) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        final int anchorWidth = anchorView.getWidth();
        final int screenHeight = anchorView.getContext().getResources().getDisplayMetrics().heightPixels;
        final int screenWidth = anchorView.getContext().getResources().getDisplayMetrics().widthPixels;
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        //偏移,否则会弹出在屏幕外
        int offset = windowWidth < anchorWidth ? (windowWidth - anchorWidth) : 0;
        //实际坐标中心点为触发view的中间
        windowPos[0] = (anchorLoc[0] + anchorWidth / 2) - (windowWidth / 2) + offset;
        windowPos[1] = isNeedShowUp ? anchorLoc[1] - windowHeight : anchorLoc[1] + anchorHeight;
        return windowPos;
    }

调用方法

int windowPos[] = calculatePopWindowPos(assistView, mRootView);
        popupWindow.showAtLocation(assistView, Gravity.NO_GRAVITY, windowPos[0], windowPos[1]);

相关文章

网友评论

    本文标题:Android PopupWindow 实现自动计算弹出位置

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