机器人检测到阻力
问题描述:
我一直在玩运动事件和拖动(所以我不会把手指从屏幕上移开 - 这不是一扔)。问题在于它只能检测到第二,第三,第四等,当我的手指移过上下拖动开始和结束点时,拖动向下或向上移动。机器人检测到阻力
查看下面的代码。当我向上拖动时计数等于2,向下拖动时计数为1。然而,只有当我将手指向上移动(计数2),然后再回落到开始向上移动的位置(计数为1)时,才会计数,而不是在等于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:
更新oldX
和oldY
,你使用它后设置diffPosY
和diffPosX
,因为您当前只在触摸开始时设置了oldX
和oldY
。所以,你已经设置diffPosY
和diffPosX
后,添加:
oldX = posX;
oldY = posY;
UPDATE
由于移动事件频繁处理,你可能要出台一些触摸污占的事实,当您将手指放在屏幕上,您可能会稍微向下移动手指,然后再向上移动而未意识到,如果慢慢地滑动,则可能会以与您想要的方式相反的方向无意中轻微地轻扫。这看起来像你在下面的评论中看到的情况。下面的代码应该有助于解决这个问题,但会对方向变化做出反应稍微慢一点:
// 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);
}