Android - 更正onTouchEvent()中状态栏的高度

时间:2012-12-27 19:35:13

标签: android statusbar ontouchevent

我在onTouchEvent(MotionEvent event)的自定义视图中回复了触摸事件。我在坐标不一致时遇到问题:event.getRaw(Y)返回包含状态栏的触摸的Y坐标,但myView.getTop()返回除状态栏之外的视图顶部的Y坐标。我使用以下hack来纠正状态栏的高度:

// Get the size of the visible window (which excludes the status bar)
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

// Get the coordinates of the touch event, subtracting the top margin
final int x = (int) event.getRawX();
final int y = (int) event.getRawY() - rect.top;

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:4)

如果您只关心相对于父视图的坐标(例如,您希望始终假设视图的左上角是0,0),则可以使用getX()和getY()代替它们原始等价物。

否则,基本上你试图相对于屏幕采用X / Y(getRawX,getRawY)并将它们转换为相对于窗口的X / Y坐标(状态栏不是窗口的一部分)。

您当前的解决方案可行,但as discussed elsewhere,getWindowVisibileDisplayFrame过去曾有过轻微破坏。更安全的方法可能是确定视图在窗口中的位置,然后使用相对于该视图的x / y坐标。

int[] coords = new int[2];
myView.getLocationInWindow(coords);

final int x = event.getRawX() - coords[0];
final int y = event.getRawY() - coords[1];