Monday, May 6, 2013

Android-Swipe Gesture Implementation

To implement Swipe Gesture we have to implement the on touch method for a particular widget

class LayoutTouchListener implements OnTouchListener{
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
}

mBaseLayout.setOnTouchListener(new LayoutTouchListener());

Then implement the SimpleOnGestureListener and do whatever you wish



SimpleOnGestureListener simpleOnGestureListener
   = new SimpleOnGestureListener(){


  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   String swipe = "";
   float sensitvity = 50;
 
   // TODO Auto-generated method stub
   if((e1.getX() - e2.getX()) > sensitvity){
    swipe += "Swipe Left\n";
   }else if((e2.getX() - e1.getX()) > sensitvity){
    swipe += "Swipe Right\n";
   }else{
    swipe += "\n";
   }
 
   if((e1.getY() - e2.getY()) > sensitvity){
    swipe += "Swipe Up\n";
   }else if((e2.getY() - e1.getY()) > sensitvity){
    swipe += "Swipe Down\n";
   }else{
    swipe += "\n";
   }
 
   gestureEvent.setText(swipe);
 
   return super.onFling(e1, e2, velocityX, velocityY);
  }
   };
 
   GestureDetector gestureDetector
   = new GestureDetector(simpleOnGestureListener);