2010-04-14 119 views
52

getLocationOnScreen()getLocationInWindow()的调用都会给我一个top/Y坐标,约为〜30px(状态/通知栏的高度)太低。 left/X坐标已死亡。坐标不正确getLocationOnScreen/getLocationInWindow

正如我上面暗示的,我认为区别是因为状态/通知栏......我可能是错的。如果我可以确定通知栏的大小,我想我可以解决这个问题,但是我很难做到这一点。

任何帮助将不胜感激。

回答

76

我最终通过确定像这样的状态/通知栏的高度解决这一问题:

View globalView = ...; // the main view of my activity/application 

DisplayMetrics dm = new DisplayMetrics(); 
this.getWindowManager().getDefaultDisplay().getMetrics(dm); 
int topOffset = dm.heightPixels - globalView.getMeasuredHeight(); 

View tempView = ...; // the view you'd like to locate 
int[] loc = new int[2]; 
tempView.getLocationOnScreen(loc); 

final int y = loc[1] - topOffset; 
+0

这在常规配置下工作,但如果当SoftInput/Keyboard打开时活动调整'globalView'高度,那么键盘高度也会计算为'topOffset',这会导致'y'值错误。 – 2014-01-06 15:09:00

+7

'int [] locInWindow = new int [2]; globalView.getLocationInWindow(locInWindow); topOffset = locInWindow [1];'//通过获得'globalView'的Y坐标来计算'topOffset' – 2014-01-06 15:39:35

+1

为我节省了很多时间,谢谢! – Justin 2014-07-18 17:36:39

5

我有同样的问题,请尝试使用

offset = myView.GetOffsetY(); 

,并通过该值,如调整ÿ坐标

coordY -= offset; 

它提供了`` - 方法的类:

class MyView extends View { 

    public int GetOffsetY() { 
    int mOffset[] = new int[2]; 
    getLocationOnScreen(mOffset); 
    return mOffset[1]; 
    } 

} 
+0

我没有看到 “getOffsetY()”。什么类是一种方法? – nimph 2010-05-03 20:55:19

+0

对不起,我无法发布方法中,在 类MyView的延伸查看 { \t公众诠释GetOffsetY() \t { INT M偏移[] =新INT [2]; \t \t getLocationOnScreen(mOffset); \t \t return mOffset [1]; \t} – user330844 2010-07-13 14:17:19

5

这里是我如何获得状态栏高度,并调整偏移量:

final int[] location = new int[2]; 
anchor.getLocationInWindow(location); // Includes offset from status bar, *dumb* 
Rect anchorRect = new Rect(location[0], location[1], 
     location[0] + anchor.getWidth(), location[1] + anchor.getHeight()); 

anchor.getRootView().findViewById(android.R.id.content).getLocationInWindow(location); 
int windowTopOffset = location[1]; 
anchorRect.offset(0, -windowTopOffset); 
+0

为什么窗口中的位置包含与状态栏的偏移量?你要求在窗口中的位置*,那么你还期望什么? – 2013-06-29 22:47:09

+1

可以假定窗口在状态栏下方,因此偏移量不包括状态栏高度。 – satur9nine 2013-06-29 23:45:01

+0

你在混淆窗口和屏幕我认为。 – 2013-07-16 00:55:28

4

此答案不包括如何获取状态栏高度,但它确实解释了getLocationOnScreen()getLocationInWindow()返回相同值的行为。

在正常活动(不是对话框)的情况下,您应该期望这两种方法返回相同的值。一个窗口在下面(如z顺序不是y坐标)放置状态栏,所以这些方法不能用来确定状态栏的高度。

https://stackoverflow.com/a/20154562/777165

+0

对话框中的观点,如果没有设置窗口全屏是真的,但如果设置如下,它工作正常'topOffset' – iXcoder 2015-03-31 02:13:32