在Android中定位弹出窗口

3

我目前正试图根据锚点元素动态定位弹出窗口在屏幕上的位置。但出现了一个问题,当我定位这个元素时,它出现在离我想要的位置左边大约100像素。例如,如果我将弹出窗口定位在靠近屏幕边缘的锚点上,则应该使其右边缘刚好出现在锚点右边缘的左侧。然而,弹出窗口却出现在屏幕的边缘。如果我从计算xPos中减去100,则可以解决这个问题。

我已经检查过我的数学计算,并逐步检查显示代码以检查值是否不正确,所以我不确定是什么原因导致了问题。不过,我正在学习安卓中的视图,所以我肯定忽略了一些东西。希望这里有人能知道怎么解决!

我在下面发布了显示代码,如果需要,我很乐意发布其他任何内容。

先谢谢您了!

    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);

我通读了代码,得到了一些数字,希望这会有所帮助: screenWidth = 1280 xPos = 765 rootWidth = 485(弹出窗口视图的宽度)。 因此,似乎在最后应该还剩下30像素,但弹出窗口却贴着屏幕右侧边缘出现。 - jmif
2个回答

3
最终找到问题所在。在上面的代码中,我使用.measure()然后使用.getMeasuredWidth/Height()来获取我要定位的视图的尺寸。不幸的是,这些实际上比视图显示后的getWidth()和getHeight()的值要小。最后我重写了onSizeChanged方法,以便可以在视图显示后跟踪其大小。一旦视图显示出来,我就获取正确的宽度/高度并立即将弹出窗口显示在其正确的位置上。
希望这对其他人有所帮助,尽管我不确定为什么getMeasuredWidth/Height返回较小的值。

哦,我一定要开始阅读文档。我真希望我早些知道onSizeChanged这个方法!*: 很长一段时间了。 - samus
嗨,你在哪个类中重写了 onSizeChanged 方法? - kalpana c

1
你能否检查一下 this.windowManager.getDefaultDisplay().getWidth(); 返回值是否正确?
如果不正确,可能会出现类似于 Android: Showing wrong screen resolution 的问题。
试着添加


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

添加到你的清单文件中。


好的,我回到设备后会检查一下。我猜返回值应该等于设备的分辨率? - jmif
刚刚检查了代码,我已经有一个最小SDK版本了,这个目标版本也需要吗? - jmif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接