2015-07-03 47 views
1

我一直在玩運動事件和拖動(所以我不會把手指從屏幕上移開 - 這不是一扔)。問題在於它只能檢測到第二,第三,第四等,當我的手指移過上下拖動開始和結束點時,拖動向下或向上移動。機器人檢測到阻力

查看下面的代碼。當我向上拖動時計數等於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; 

回答

3

如果我明白你正確地做什麼,我認爲你需要在你的case MotionEvent.ACTION_MOVE:更新oldXoldY,你使用它後設置diffPosYdiffPosX,因爲您當前只在觸摸開始時設置了oldXoldY。所以,你已經設置diffPosYdiffPosX後,添加:

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); 
}