Incorrect Coordinates From getLocationOnScreen/getLocationInWindow
调用
如上所述,我相信差异是由于状态/通知栏...我可能是错的。 我想如果可以确定通知栏的大小,就可以解决此问题,但是我无法做到这一点。
任何帮助将不胜感激。
我最终通过确定状态/通知栏的高度来解决此问题,如下所示:
1 2 3 4 5 6 7 8 9 10 11 | 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; |
这是我想要获取状态栏高度并调整偏移量的方法:
1 2 3 4 5 6 7 8 | 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); |
我遇到同样的问题,请尝试使用
1 | offset = myView.GetOffsetY(); |
并根据该值调整您的Y坐标,例如
1 | coordY -= offset; |
提供``-方法:
1 2 3 4 5 6 7 8 9 | class MyView extends View { public int GetOffsetY() { int mOffset[] = new int[2]; getLocationOnScreen( mOffset ); return mOffset[1]; } } |
此答案不包括如何获取状态栏的高度,但确实说明了
在正常活动(不是对话框)的情况下,您应该期望这两个方法返回相同的值。 窗口在状态栏的下方(如z顺序而不是y坐标)布局,因此无法使用这些方法确定状态栏的高度。
https://stackoverflow.com/a/20154562/777165