android 检测到拖动

android detecting a drag

我一直在玩运动事件和拖动(所以我没有将手指从屏幕上移开 - 这不是猛击)。问题是它只检测第二个、第三个、第四个等等,当我的手指移过向上拖动或向下拖动开始和结束的点时向下或向上拖动。

见下面的代码。向上拖动时计数等于 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;

如果我理解您正在尝试正确执行的操作,我认为您需要更新 case 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);
}