/** * 计算mView在view周围的位置 * * @param view * * @param mMargin mView与view或边界的间距 * * titleBarHeight 标题栏的高度 * mContext当前的Activity */ private void aroundView(View view, float mMargin) { if (view == null) { return; } boolean showLeft; boolean showRight; boolean showUp; boolean showDown; if (titleBarHeight == 0) { Rect frame = new Rect(); ((Activity) mContext).getWindow().getDecorView() .getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int contentTop = ((Activity) mContext).getWindow() .findViewById(Window.ID_ANDROID_CONTENT).getTop(); titleBarHeight = contentTop - statusBarHeight; } int width = mView.getWidth();//如果Params获取不到长宽,就在Dialog显示之后获取长宽 int height = mView.getHeight(); android.view.ViewGroup.LayoutParams lp = mView.getLayoutParams(); if(lp!=null){ //主要以这步计算长宽为主,如果获取不到再退而求其次 width = lp.width; height = lp.height; } if(width == 0 && height == 0){//如果两种方法都获取不到长宽,则默认给一个值,下次用getWidth获得 width = (int) (mWinWidth/2 - mMargin); height = (int) (mWinheight/2 - mMargin); } showLeft = showRight = showUp = showDown = false; if ((view.getX() - mMargin) >= width) {//左 showLeft = true; showRight = false; } if ((mWinWidth - view.getX() - mMargin) >= width) {//右 showLeft = false; showRight = true; } if ((view.getY() - mMargin) >= height) {//上 showUp = true; showDown = false; } if ((mWinheight - view.getY() - mMargin) >= height) {//下 showUp = false; showDown = true; } // 根据计算,设置坐标 if (showLeft) { mView.setX(view.getX() + view.getWidth() - width - mMargin); } else if (showRight) { mView.setX(view.getX() + mMargin); } else { mView.setX(mWinWidth - mMargin - width); } // 根据计算,设置坐标 if (showLeft) { mView.setX(view.getX() + view.getWidth() - width - mMargin); } else if (showRight) { mView.setX(view.getX() + mMargin); } else { mView.setX(mWinWidth - mMargin - width);//如果宽度偏大,则右对齐 } if (showUp) { mView.setY(view.getY() - height + titleBarHeight - mMargin); } else if (showDown) { mView.setY((view.getY() + view.getHeight()) + titleBarHeight + mMargin); } else { //如果高度偏大,在下面显示 mView.setY((view.getY() + view.getHeight()) + titleBarHeight + mMargin); } }
本博客原地址: