2015-06-10 224 views
2

如何檢測輕掃手勢onTouch方法?當我輕掃時,我想要執行兩個動作中的一個,而當我點擊時則需要執行其中一個動作。需要知道如何說明點擊和輕掃之間的區別。檢測輕掃手勢

這裏是我的代碼:

@Override 
public boolean onTouch(View v, MotionEvent event) { 
if (event.getAction() == MotionEvent.ACTION_MOVE) { 
    mGestureDetector.onTouchEvent(event); 
} 
switch(event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     x1 = event.getX(); 
     y1 = event.getY(); 
     break; 
    case MotionEvent.ACTION_UP: 
     x2 = event.getX(); 
     y2 = event.getY(); 

     float deltaX = x2 - x1; 
     float deltaY = y2 - y1; 

     if (Math.abs(deltaX) > MIN_DISTANCE) { 
      mGestureDetector.onTouchEvent(event); 
     }else if (Math.abs(deltaX) < MIN_DISTANCE) { 
      mGestureDetector.onTouchEvent(event); 
     }else if (Math.abs(deltaY) > MIN_DISTANCE) { 
      mGestureDetector.onTouchEvent(event); 
     }else if (Math.abs(deltaY) < MIN_DISTANCE) { 
      mGestureDetector.onTouchEvent(event); 
     } 
     break; 
} 
return true; 

}

回答

0

這裏是你可以做什麼,在this link 發現在活動的onCreate,添加此。

final GestureDetector gestureDetector = new GestureDetector(new GestureListener()); 
calendar.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(final View view, final MotionEvent event) { 
    if (gestureDetector.onTouchEvent(event)) { 
     return false; 
    } 
    return true; 
    } 
}); 

這裏是GestureDetector類

class GestureListener extends SimpleOnGestureListener { 
    @Override 
    public boolean onSingleTapConfirmed(MotionEvent event) { 
    // Trigger the touch event on the calendar 
     calendar.onTouchEvent(event); 
     return super.onSingleTapUp(event); 
    } 

@Override 
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
    ViewConfiguration viewConfiguration = ViewConfiguration.get(EventsActivity.this); 
    int minSwipeDistance = viewConfiguration.getScaledPagingTouchSlop(); 
    int minSwipeVelocity = viewConfiguration.getScaledMinimumFlingVelocity(); 
    int maxSwipeOffPath = viewConfiguration.getScaledTouchSlop(); 
    if (Math.abs(e1.getY() - e2.getY()) > maxSwipeOffPath) { 
     return false; 
    } 

    if (Math.abs(velocityX) > minSwipeVelocity) { 
    // Right to left swipe 
     if (e1.getX() - e2.getX() > minSwipeDistance) { 
     calendar.nextMonth(); 
    } 

    // Left to right 
    else if (e2.getX() - e1.getX() > minSwipeDistance) { 
     calendar.previousMonth(); 
    } 

    // Call some app-related functions to update the display 
    displayDate(calendar.getMonth(), calendar.getYear()); 
    } 
    return false; 
} 
} 
+0

感謝您的答覆。它不工作。我試圖在自己的軟鍵盤中實現手勢,以便將屏幕從qwerty更改爲數字,例如,如果您只需點擊一個可以打印該字母的單個字母。我的鍵盤用onSwipe方法工作得很好,但它不準確。我發佈的代碼比您的更準確。所以,如果你能告訴我如何區分觸摸和滑動。我嘗試了我發佈的代碼中的某些內容,但我只能輕掃一下,不能點擊單個字母。 – jelic98