Pages

Wednesday 9 November 2011

Swipe event in android ScrollView

If your Layout have scroll view then its difficult to detect the swipe event into scroll view using Gesture detector. After following several solutions and looking on stack overflow I made some changes which work great in detecting swipe in scroll view. If you use Gesture and override touch event you will be able to detect event but the scollview scroll will not work so try this solution.
import android.app.Activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;

public class ActivitySwipeDetector implements View.OnTouchListener {

 private Activity activity;
 static final int MIN_DISTANCE = 100;
 private float downX, downY, upX, upY;

 public ActivitySwipeDetector(final Activity activity) { 
  this.activity = activity;
 }

 public final void onRightToLeftSwipe() {
  Log.i("RightToLeftSwipe!");
 }

 public void onLeftToRightSwipe(){
  Log.i( "LeftToRightSwipe!");
 }

 public void onTopToBottomSwipe(){
  Log.i( "onTopToBottomSwipe!");
 }

 public void onBottomToTopSwipe(){
  Log.i( "onBottomToTopSwipe!");
 }

 public boolean onTouch(View v, MotionEvent event) {
  switch(event.getAction()){
  case MotionEvent.ACTION_DOWN: {
   downX = event.getX();
   downY = event.getY();
   //   return true;
  }
  case MotionEvent.ACTION_UP: {
   upX = event.getX();
   upY = event.getY();

   float deltaX = downX - upX;
   float deltaY = downY - upY;

   // swipe horizontal?
   if(Math.abs(deltaX) > MIN_DISTANCE){
    // left or right
    if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
    if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
   } else { Log.i( "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); }

   // swipe vertical?
   if(Math.abs(deltaY) > MIN_DISTANCE){
    // top or down
    if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
    if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
   } else { Log.i( "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); }

   //     return true;
  }
  }
  return false;
 }
}

3 comments:

  1. Can you help me with that?It does not work even with no Scrollview in the layout.

    ReplyDelete
  2. The horizontal detection doesn't work properly. It only recognizes the horizontal swipe if its done in a diagonal, that is swiping from one point A on the left side, moving to a pint B on the right side that is either above or below where point A was located on the left side. However if the swipe begins at point A on the left moving strictly horizontally towards a pint B on the right, with no change in the Y coordinate, then the swipe isn't detected. Any ideas as to why this might be? Or how it can be solved?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete