2011-11-17 66 views
3

我目前正在尝试在基于锚点元素的屏幕上动态地定位弹出窗口。出于某种原因,当我定位这个元素时,它在我想要的位置左侧出现大约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); 
+0

我通过代码加强,希望这将有助于获得一些数字: 屏幕宽度= 1280 XPOS = 765 rootWidth = 485(弹出窗口的视图的宽度),所以它看起来像我应该有30像素左结束时弹出窗口,但弹出窗口显示为与屏幕右边缘齐平 –

回答

3

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

希望这可以帮助别人,但我不知道为什么getMeasuredWidth/Height返回的值较小。

+0

哦,伙计,我完全会开始阅读文档的人。我很希望我知道onSizeChanged a *前一阵子! *:很长一段时间。 – samosaris

+0

嗨,你重写onSizeChanged在哪个类? –

1

你能检查返回的this.windowManager.getDefaultDisplay().getWidth();的值是否正确?

如果不是,它可能会在Android: Showing wrong screen resolution

尝试增加

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

到您的清单文件是一个类似的问题作为。

+0

是的我会检查当我回到设备时,我假设返回的值应该等于设备的分辨率? –

+0

刚刚检查了代码,我确实有一个min sdk版本,是否也需要这个目标版本? –