好的,既然似乎没有更简单的答案,我将为更多读者提供我自己相对简单的解决方案,不需要手势检测。
首先,您需要接收拖动事件的视图,其次是
拖动事件 ifself (或至少 x 和 y 坐标)。
通过获取视图位置和一些简单的添加,您可以获得
原始触摸位置。
此方法已使用 显示指针位置 开发人员选项进行测试
提供正确的数据。
计算方法如下:
/**
* @param item the view that received the drag event
* @param event the event from {@link android.view.View.OnDragListener#onDrag(View, DragEvent)}
* @return the coordinates of the touch on x and y axis relative to the screen
*/
public static Point getTouchPositionFromDragEvent(View item, DragEvent event) {
Rect rItem = new Rect();
item.getGlobalVisibleRect(rItem);
return new Point(rItem.left + Math.round(event.getX()), rItem.top + Math.round(event.getY()));
}
在你的 onDragListener 实现中调用这个方法:
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
//etc etc. do some stuff with the drag event
break;
case DragEvent.ACTION_DRAG_LOCATION:
Point touchPosition = getTouchPositionFromDragEvent(v, event);
//do something with the position (a scroll i.e);
break;
default:
}
return true;
}
附加:
如果您想确定触摸是否在特定视图内,您可以
做这样的事情:
public static boolean isTouchInsideOfView(View view, Point touchPosition) {
Rect rScroll = new Rect();
view.getGlobalVisibleRect(rScroll);
return isTouchInsideOfRect(touchPosition, rScroll);
}
public static boolean isTouchInsideOfRect(Point touchPosition, Rect rScroll) {
return touchPosition.x > rScroll.left && touchPosition.x < rScroll.right //within x axis / width
&& touchPosition.y > rScroll.top && touchPosition.y < rScroll.bottom; //withing y axis / height
}
也可以基于此方案在ListView上实现平滑滚动。
这样用户就可以将一个项目拖出列表,并通过将项目拖动到列表视图的顶部或底部来滚动列表。
干杯。