android检测拖动

时间:2015-07-03 13:14:23

标签: android events motion

我一直在玩动作事件和拖拽(所以我不会把手指从屏幕上抬起来 - 这不是一件事)。问题是它只能检测到第二个,第三个,第四个等等,当我的手指移动经过向上拖动或向下拖动开始和结束的点时,拖动向下或向上移动。

见下面的代码。我向上拖动时计数等于2,向下拖动时计数等于1。但是,它只计算在例如我向上移动手指(计数2)然后向下移动超过我开始向上移动的时间点(将计数为1),而不是在等于2的那个之前,这个当我向后移动时它继续向下只有当我移动到我改变方向然后向下移动时才计算2。但是为什么它不会在这些点之前将其视为拖累,因为那些方向上的任何移动都应该是拖累。我该如何解决这个问题?

这是我测试它的简单代码:

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:

        oldX = (int) event.getRawX();
        oldY = (int) event.getRawY();


        break;

    case MotionEvent.ACTION_MOVE:

        posY = (int) event.getRawY();
        posX = (int) event.getRawX();


        diffPosY = posY - oldY;
        diffPosX = posX - oldX;

       if (diffPosY > 0){//down

            count  = 1;

        }
        else//up
        {   
            count = 2;

        }

        break;

1 个答案:

答案 0 :(得分:3)

如果我了解您正在尝试正确执行的操作,我认为您需要在oldX之后更新oldYcase MotionEvent.ACTION_MOVE:设置diffPosYdiffPosX是因为您当前只在触摸开始时设置oldXoldY。因此,在您设置diffPosYdiffPosX之后,请添加:

oldX = posX;
oldY = posY;

<强>更新

因为经常处理运动事件,你可能想要引入一些触摸斜率,以说明当你将手指放在屏幕上时,你可能会在你向上移动之前稍微向下移动而没有意识到它,如果你慢慢地滑动,你可能会无意中轻轻地向相反的方向滑动,就像你认为你要走的那样。这看起来就像你在下面的评论中看到的那样。以下代码应该有助于解决这个问题,但会对方向更改做出稍微缓慢的反应:

// Get the distance in pixels that a touch can move before we
// decide it's a drag rather than just a touch. This also prevents
// a slight movement in a different direction to the direction
// the user intended to move being considered a drag in that direction.
// Note that the touchSlop varies on each device because of different
// pixel densities.
ViewConfiguration vc = ViewConfiguration.get(context);
int touchSlop = vc.getScaledTouchSlop();

// So we can detect changes of direction. We need to
// keep moving oldY as we use that as the reference to see if we
// are dragging up or down.
if (posY - oldY > touchSlop) {
    // The drag has moved far enough up the Y axis for us to
    // decide it's a drag, so set oldY to a new position just below
    // the current drag position. By setting oldY just below the
    // current drag position we make sure that if while dragging the
    // user stops their drag and accidentally moves down just by a
    // pixel or two (which is easily done even when the user thinks
    // their finger isn't moving), we don't count it as a change of
    // direction, so we use half the touchSlop figure as a small
    // buffer to allow a small movement down before we consider it
    // a change of direction.
    oldY = posY - (touchSlop / 2);
} else if (posY - oldY < -touchSlop) {
    // The drag has moved far enough down the Y axis for us to
    // decide it's a drag, so set oldY to a new position just above
    // the current drag position. This time, we set oldY just above the
    // current drag position.
    oldY = posY + (touchSlop / 2);
}