在Android中定位弹出窗口

时间:2011-11-17 17:37:28

标签: android

我目前正在尝试根据锚元素在屏幕上动态定位弹出窗口。出于某种原因,当我定位这个元素时,它出现在我想要它的左边大约100px。例如,如果我将其放置在靠近屏幕边缘的锚点上,弹出窗口应该出现,其右边缘位于锚点右边缘的左侧。但是,弹出窗口显示为与屏幕边缘齐平。如果我从计算的xPos中减去100,那么它可以正常工作。

我已经检查了我的数学并且已经通过显示代码来检查值是否未正确显示,所以我不确定导致问题的原因。我只是在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);

2 个答案:

答案 0 :(得分:3)

最后找出了问题所在。在上面的代码中,我使用.measure()然后.getMeasuredWidth / Height()来获取我想要定位的视图的度量。不幸的是,在显示视图后,这些值实际上小于getWidth()和getHeight()的值。我最终覆盖onSizeChanged,以便在显示视图后跟踪大小。显示视图后,我会抓住正确的宽度/高度,并立即在正确的位置显示弹出窗口。

希望这有助于其他人,但我不确定为什么getMeasuredWidth / Height返回较小的值。

答案 1 :(得分:1)

您可以检查this.windowManager.getDefaultDisplay().getWidth();的返回值是否正确吗?

如果没有,则可能与Android: Showing wrong screen resolution

中的问题类似

尝试添加

<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />

到你的清单文件。

相关问题