我目前正在尝试在基于锚点元素的屏幕上动态地定位弹出窗口。出于某种原因,当我定位这个元素时,它在我想要的位置左侧出现大约100px。例如,如果我将它放置在靠近屏幕边缘的锚点上,弹出式窗口应该以右边缘出现在锚点右边的左边。但是,弹出窗口显示为与屏幕边缘齐平。如果我从计算的xPos减去100,那么它工作正常。在Android中定位弹出窗口
我检查了我的数学,并通过显示代码来检查值是不是出现错误,所以我不知道是什么导致问题。我只是在android中学习视图,所以我确定我忽略了一些东西。希望这里有人会知道!
我已经发布了下面的显示代码,如果需要,我会很高兴发布任何其他内容。
在此先感谢!
int[] location = new int[2];
this.anchor.getLocationOnScreen(location);
Rect anchorRect =
new Rect(location[0], location[1], location[0] + this.anchor.getWidth(), location[1]
+ this.anchor.getHeight());
this.anchorRectangle = anchorRect;
this.root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.root.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int rootWidth = this.root.getMeasuredWidth();
int rootHeight = this.root.getMeasuredHeight();
int screenWidth = this.windowManager.getDefaultDisplay().getWidth();
int xPos, yPos;
// Align popup with right side if the root is wider than anchor
// Align with left otherwise
if (rootWidth > anchorRect.right - anchorRect.left) {
xPos = anchorRect.right - rootWidth;
} else {
xPos = anchorRect.left + 15;
}
// Correct for spilling off the edge
if (xPos + rootWidth > screenWidth)
xPos = screenWidth - rootWidth - 20;
// xPos = ((screenWidth - rootWidth)/2) + xOffset;
yPos = anchorRect.top - rootHeight + yOffset;
this.rootRectangle = new Rect(xPos, yPos, xPos + rootWidth, yPos + rootHeight);
boolean onTop = true;
// display on bottom
if(rootHeight > anchorRect.top) {
onTop = false;
yPos = anchorRect.bottom + yOffset;
this.window.setAnimationStyle(R.anim.grow_from_top);
}
this.window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos);
我通过代码加强,希望这将有助于获得一些数字: 屏幕宽度= 1280 XPOS = 765 rootWidth = 485(弹出窗口的视图的宽度),所以它看起来像我应该有30像素左结束时弹出窗口,但弹出窗口显示为与屏幕右边缘齐平 –