【问题标题】:Get touch position while dragging拖动时获取触摸位置
【发布时间】:2015-05-29 14:56:55
【问题描述】:

我有一些我喜欢拖拽的观点。意见在 一个 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 组合触摸的位置 与视图位置。但是没有更好的方法吗?

【问题讨论】:

  • 欢迎设计您自己的自定义手势。我会环顾四周,看看人们是如何做手势的。这是一个 fling stackoverflow.com/questions/4139288/… 的示例,或者是的,您可以执行 Ps:但是如果您在布局中拖动几层深的东西,则需要进行一些计算才能获得触摸位置

标签: android drag-and-drop touch


【解决方案1】:

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

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

干杯。

【讨论】:

  • 你好,请你正确的实现流程我被困在这个类型的问题中,如果它的演示那么它会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
相关资源
最近更新 更多