我想根据锚位置显示弹出窗口。
目前它正在锚点的左上角显示弹出窗口,但我想在锚点的中心位置显示弹出窗口,而不是左侧。
这是我的代码:
public void show (View anchor) {
preShow();
int xPos, yPos,arrowPos;
mDidAction = false;
int[] location = new int[2];
anchor.getLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1]
+ anchor.getHeight());
//mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootHeight = mRootView.getMeasuredHeight();
if (rootWidth == 0) {
rootWidth = mRootView.getMeasuredWidth();;
}
int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
int screenHeight = mWindowManager.getDefaultDisplay().getHeight();
//automatically get X coord of popup (top left)
if ((anchorRect.left + rootWidth) > screenWidth) {
xPos = anchorRect.left - (rootWidth-anchor.getWidth());
xPos = (xPos < 0) ? 0 : xPos;
arrowPos = anchorRect.centerX()-xPos;
} else {
if (anchor.getWidth() > rootWidth) {
xPos = anchorRect.centerX() - (rootWidth/2);
} else {
xPos = anchorRect.left;
}
arrowPos = anchorRect.centerX()-xPos;
}
int dyTop = anchorRect.top;
// //automatically get X coord of popup (top left)
int dyBottom = screenHeight - anchorRect.bottom;
boolean onTop = (dyTop > dyBottom) ? true : false;
if (onTop) {
if (rootHeight > dyTop) {
yPos = 15;
LayoutParams l = mScroller.getLayoutParams();
l.height = dyTop - anchor.getHeight();
} else {
yPos = anchorRect.top - rootHeight;
}
} else {
yPos = anchorRect.bottom;
if (rootHeight > dyBottom) {
LayoutParams l = mScroller.getLayoutParams();
l.height = dyBottom;
}
}
mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos,yPos);
}
请建议
答案 0 :(得分:0)
而不是这个
mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos,yPos);
试试这可能对你有帮助......
mWindow.showAtLocation(anchor, Gravity.CENTER, 0, 0);
或
mWindow.showAtLocation(anchor, Gravity.CENTER, anchorwidth / 2, anchorheight / 2);