【发布时间】:2012-12-13 04:07:32
【问题描述】:
我在onTouchEvent(MotionEvent event) 的自定义视图中响应触摸事件。我遇到了坐标不一致的问题:event.getRaw(Y) 返回包括状态栏在内的触摸的 Y 坐标,但 myView.getTop() 返回不包括状态栏的视图顶部的 Y 坐标。我采用了以下技巧来纠正状态栏的高度:
// 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;
有没有更好的解决方案?
【问题讨论】:
-
您希望最终的 X/Y 值采用什么形式?包括状态栏,排除它们,还是相对于接收到触摸事件的父视图?
-
排除状态栏。例如,我的自定义视图从 y=0 开始,所以我希望该视图的最顶部是 y=0 而不是 y=38 或其他东西。
-
在这种特殊情况下,为什么 getX 和 getY 不适合您,因为它们是相对于视图的左上角的?
标签: android statusbar touch-event