Skip to main content

Easy swipe gesture handling on android

Recently I wanted to implement swipe functionality for activity in my android app but couldn't find a nice and simple example that would explain what do you really need to do. There are multiple sites that are bloated with code, but somehow I couldn't believe that to implement such a simple (and kinda basic if you think about it) functionality you need to write tens of lines of code.

So if you're like me, looking for a simple and elegant solution for swipe gesture handling, here it is...

First some theory - to implement swipe you will need to:
1. Create a GestureDetector
2. Create an OnGestureListener by extending GestureDetector.SimpleOnGestureListener
3. Implement onFling method in listener created in step 2
4. Handle the onTouchEvent in your activity

Now let's jump to the code:
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;

public class MySwipeSupportedActivity extends Activity {
 // swipe gesture constants
 private static final int SWIPE_MIN_DISTANCE = 120;
 private static final int SWIPE_THRESHOLD_VELOCITY = 200;

 private GestureDetector gestureDetector;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  gestureDetector = new GestureDetector(this, new OnSwipeGestureListener());
  // TODO: any other logic you require in the onCreate
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  return gestureDetector.onTouchEvent(event);
 }

 /**
  * Class handling swipe gesture
  */
 private class OnSwipeGestureListener extends 
GestureDetector.SimpleOnGestureListener {
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, 
float velocityX, float velocityY) {
   float deltaX = e2.getX() - e1.getX();
   if ((Math.abs(deltaX) < SWIPE_MIN_DISTANCE) 
|| (Math.abs(velocityX) < SWIPE_THRESHOLD_VELOCITY)) {
    return false; // insignificant swipe
   } else {
    if (deltaX < 0) { // left to right
     handleSwipeLeftToRight();
    } else { // right to left
     handleSwipeRightToLeft();
    }
   }
   return true;
  }
 }

 private void handleSwipeLeftToRight() {
  // TODO: implement the business logic here
 }

 private void handleSwipeRightToLeft() {
  // TODO: implement the business logic here
 }
}

That's it. Enjoy your swipe-enabled activity :)

Comments

  1. Nice post...very helpful !!!!

    ReplyDelete
  2. Great!
    This is the most simple way of doing this that I have seen...

    ReplyDelete

Post a Comment

Popular posts from this blog

Eclipse + EGit - "The authenticity of host ... can't be established" challenge

Recently while writing new Android code I decided that it's the highest time to have a Git repository not only on my hard drive, but also safe in the Internet. After quick search and finding out that I have accounts at almost every popular service that provides Git hosting, I figured out that one that covers everything I need (wiki, bug tracking, code hosting, forums) is the good old sourceforge. I used it also with no problems few months ago on another mobile project, so I was hoping that pushing code there will be a piece of cake. But then when I tried to do it (after configuring the project on the sourceforge site), I got very interesting error: ssh://USER@git.code.sf.net:22: org.eclipse.jgit.transport.CredentialItem$YesNoType:The authenticity of host 'git.code.sf.net' can't be established. RSA key fingerprint is 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d. Are you sure you want to continue connecting? In theory it's nothing bad, you press the "Y...

Rendering AdMob view on Canvas (SurfaceView) in android

If you're wondering how put a working AdMob view into your SurfaceView and are tired of looking in the Internet for solution (somehow most suggestions that I found on forums didnt work), here it is... Assumptions: A. We request the ad on creation (you may want to refresh it later though...) B. The AdView is put on the bottom of the screen C. It's a production ready code, but if you want to test it - add testDevices to the adRequest D. You've already set AndroidManifest properly as described in the Getting Started tutorial 1. In the activity that initializes your SurfaceView add a field representing your adView, for example: private AdView adView; 2. In the onCreate method of the same activity put the following code: // window manager preparation WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams(); windowParams.gravity = Gravity.BOTTOM; windowParams.x = 0; windowParams.y = 0; windowParams.height = WindowManager.Lay...

How to make Logitech Trackball Marble Wheel work

If you bought Trackball Marble from Logitech, the first challenge you encounter is probably related to the lack of the wheel button. Unfortunately the software provided with the device for Windows doesn't help (neither Universal or Auto Search aren't really working as I was expecting). Internet suggests mostly one option, app called Marble Mouse Scroll Wheel http://marble-mouse-scroll-wheel.software.informer.com/ To some extent it works, but I wasn't able to make it work in google maps or in picture viewer. Moreover setting where crashing very often (I am running windows 7 64 bits). Fortunately there is a way to have a semi-wheel button behavior with this trackball, but with a different software - X-Mouse Button Control: http://www.highrez.co.uk/downloads/XMouseButtonControl.htm Setup Mouse button 4 and 5 as wheel up and wheel down. Then also update Logitech SetPoint settings to replace the behavior of those button to default. Voila - now you can emulate wheel ...