android检测拖动

Kaa*_*aal 3 events android 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;
Run Code Online (Sandbox Code Playgroud)

Hex*_*ugs 5

如果我理解你想要正确地做什么,我认为你需要更新oldX,并oldY在你的case MotionEvent.ACTION_MOVE:,你用它来集之后diffPosY,并diffPosX因为你目前只设置oldXoldY触摸启动时。因此,在设置diffPosYand 之后diffPosX,添加:

oldX = posX;
oldY = posY;
Run Code Online (Sandbox Code Playgroud)

更新

由于运动事件被频繁处理,您可能想要引入一些触摸倾斜来解释这样一个事实,即当您将手指放在屏幕上时,您可能会在不知不觉中向上移动之前稍微向下移动它,并且如果您缓慢滑动您可能会不经意地向与您认为要去的方向相反的方向轻轻滑动。这看起来就像你在下面的评论中看到的那样。以下代码应该有助于解决这个问题,但会使其对方向变化的反应稍慢:

// 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);
}
Run Code Online (Sandbox Code Playgroud)