拖动时获取触摸位置

Get touch position while dragging

我有一些我喜欢拖来拖去的观点。意见在 一个 LinearLayout,它本身在一个滚动视图中。

我想获取当前手指(触摸)的位置,以 在我的滚动视图上平滑滚动,具体取决于 当前拖动的高度。

长按 查看内置监听器 startDrag

view.startDrag(null, shadowBuilder, view, 0);

我也能得到拖动的相对位置 在

当前悬停的视图上
view.setOnDragListener(new OnDragListener() {
        @Override
        public boolean onDrag(View v, DragEvent event) {
            //get event positions
        }
    });

但这只适用于拖动阴影当前所在的视图 而 DragEvent 只提供相对位置,不提供原始位置。

我需要的是拖动发生时手指的位置。不幸的是,拖动时所有的 onTouchEvents 都被消耗了。

有人知道我是如何让它工作的吗?

Ps:我目前使用的一种有效方法是计算 通过 dragEvent.relativePosition 组合的触摸位置 与视图位置。但是有没有更好的方法呢?

好的,因为似乎没有更简单的答案,我将提供我自己的相对简单的解决方案供更多读者使用,无需手势检测。

首先你需要接收拖动事件的视图,然后是 拖动事件 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的平滑滚动。 这样用户就可以将项目拖出列表,并通过将项目拖到列表视图的顶部或底部来滚动列表。

干杯。