Android中的popupWindow

334 阅读1分钟

指定展示位置

showAtLocation()

计算展示位置

/**
     * 计算出来的位置,y方向就在anchorView的上面和下面对齐显示,x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化,就可以适当自己额外加入偏移来修正
     * @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[3];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtil.getScreenHeight(anchorView.getContext());
        final int screenWidth = ScreenUtil.getScreenWidth(anchorView.getContext());
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = getTotalHeightofListView();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth /2;//可以根据OnTouchListener来根据手指位置显示
            windowPos[1] = anchorLoc[1] - windowHeight + anchorHeight / 2;
            windowPos[2] = 1;//动画类型标记
        } else {
            windowPos[0] = screenWidth /2;
            windowPos[1] = anchorLoc[1] + anchorHeight / 2;
            windowPos[2] = -1;
        }
        return windowPos;
    }

指定动画

setAnimationStyle()

点击外部消失

setBackgroundDrawable()//缺失背景则无效
setOutsideTouchable()
setFocusable()

阴影

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            popup.setElevation(ScreenUtil.getPxByDp(10));
        }