安卓如何检测拖动操作

3
我一直在尝试使用运动事件和拖动(所以我没有把手指从屏幕上拿开 - 这不是扔)。问题是,只有当我的手指移过向上或向下拖动开始和结束的点时,它才会检测到第二、第三、第四等拖动向下或向上移动。
请参见下面的代码。当我向上拖动时,计数为2,当我向下拖动时,计数为1。然而,只有当我向上移动手指(计数为2),然后再向下移动超过我开始向上移动的点(这将是计数为1的点)时,它才会计数,而不是在那之前,这应该是2,当我向上移动时,它继续计数为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个回答

5

如果我正确理解您的意图,我认为在MotionEvent.ACTION_MOVE中使用oldXoldY设置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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接