Android swipe gesture implementation
I was looking for a simple solution how to swipe screens left and right.
I found some on this page “Android Gestures“
It is so simple, that I do want to show it here. But I needed change a little code for my needs and Eclipse asked two times to remove “@Override” option.
First, create SimpleGestureFilter class in your projest:
public class SimpleGestureFilter extends SimpleOnGestureListener{
public final static int SWIPE_UP = 1;
public final static int SWIPE_DOWN = 2;
public final static int SWIPE_LEFT = 3;
public final static int SWIPE_RIGHT = 4;
public final static int MODE_TRANSPARENT = 0;
public final static int MODE_SOLID = 1;
public final static int MODE_DYNAMIC = 2;
private final static int ACTION_FAKE = -13; //just an unlikely number
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
private int mode = MODE_DYNAMIC;
private boolean running = true;
private boolean tapIndicator = false;
private Activity context;
private GestureDetector detector;
private SimpleGestureListener listener;
public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {
this.context = context;
this.detector = new GestureDetector(context, this);
this.listener = sgl;
}
public void onTouchEvent(MotionEvent event){
if(!this.running)
return;
boolean result = this.detector.onTouchEvent(event);
if(this.mode == MODE_SOLID)
event.setAction(MotionEvent.ACTION_CANCEL);
else if (this.mode == MODE_DYNAMIC) {
if(event.getAction() == ACTION_FAKE)
event.setAction(MotionEvent.ACTION_UP);
else if (result)
event.setAction(MotionEvent.ACTION_CANCEL);
else if(this.tapIndicator){
event.setAction(MotionEvent.ACTION_DOWN);
this.tapIndicator = false;
}
}
//else just do nothing, it's Transparent
}
public void setMode(int m){
this.mode = m;
}
public int getMode(){
return this.mode;
}
public void setEnabled(boolean status){
this.running = status;
}
public void setSwipeMaxDistance(int distance){
this.swipe_Max_Distance = distance;
}
public void setSwipeMinDistance(int distance){
this.swipe_Min_Distance = distance;
}
public void setSwipeMinVelocity(int distance){
this.swipe_Min_Velocity = distance;
}
public int getSwipeMaxDistance(){
return this.swipe_Max_Distance;
}
public int getSwipeMinDistance(){
return this.swipe_Min_Distance;
}
public int getSwipeMinVelocity(){
return this.swipe_Min_Velocity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final float xDistance = Math.abs(e1.getX() - e2.getX());
final float yDistance = Math.abs(e1.getY() - e2.getY());
if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
return false;
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
boolean result = false;
if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
if(e1.getX() > e2.getX()) // right to left
this.listener.onSwipe(SWIPE_LEFT);
else
this.listener.onSwipe(SWIPE_RIGHT);
result = true;
}
else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
if(e1.getY() > e2.getY()) // bottom to up
this.listener.onSwipe(SWIPE_UP);
else
this.listener.onSwipe(SWIPE_DOWN);
result = true;
}
return result;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
this.tapIndicator = true;
return false;
}
@Override
public boolean onDoubleTap(MotionEvent arg0) {
this.listener.onDoubleTap();;
return true;
}
@Override
public boolean onDoubleTapEvent(MotionEvent arg0) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent arg0) {
if(this.mode == MODE_DYNAMIC){ // we owe an ACTION_UP, so we fake an
arg0.setAction(ACTION_FAKE); //action which will be converted to an ACTION_UP later.
this.context.dispatchTouchEvent(arg0);
}
return false;
}
static interface SimpleGestureListener{
void onSwipe(int direction);
void onDoubleTap();
}
}
then implement Gesture Listener in your code. In my case it looked as following:
public class myClass extends ListActivity implements SimpleGestureListener{
private SimpleGestureFilter detector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprog);
detector = new SimpleGestureFilter(this,this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
@Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
@Override
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
}
Simple enough. Thanks!
[...] I was looking forward to learn how Swipe gestures can be implemented in android and came across this very nicely written blog which has all the code needed to implement the swipe gestures - http://misha.beshkin.lv/android-swipe-gesture-implementation/ [...]
Hi,
What should be there inside R.layout.myprog xml file.
Could you please help me.
Thanks in advance
Shibha,
nothing special – just your own layout xml file.
Thanks a lot. This code more helped.
Thanks a lot.
Thanks a bunch! This really works well.
Unfortunately application has stopped message is coming .Someone please help me
Thank you sooo much!!!!! this blog post has helped me out so much! my only issue is that the toasts do not appear every time I swipe, however this is the only tutorial out of the tens of them I have already tried that actually worked!!!!! Thank you once again.
Hi Alex,
The toasts may not appear based on the length of your swipes.
Note the following values:
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
These values control the swipe, anything shorter than a 100 and longer than 350 is ignored. Which depending on your screen size could be a very short distance as it states in the Documentation that “For a touch screen, reports the absolute X screen position of the center of the touch contact area. The units are display pixels.”
Hope that clears it up for you.
Thanks to OP for this great and simple to implement tutorial, came in really handy when I needed to figure out how it worked
Will this work for swiping back and forth between different layouts in a fragment, without affecting the other fragment(s) in the activity? I realize that there would be some modifications needed for sure, but would the changes required be extensive? Anyone? And thanks for the post.
Works directly, is rare these days.
Many thanks
Thanks!
thanks,But can I set swipe action for a single items like image or listview,etc.If anybody knows please tell me where to put that code.
Sir, i have implemented it successfully but messages in the toasts do not appear whenever i swipe…. please help!!!!!!!!!!!!!!
try to use myClass.this instead of this in Toast.
Sir, actually i was trying to swipe between tabs. So i have not implemented toast. instead of toast, i used intent. but implementing toast also does not help.
I haven’t try it on different Activities.
I think that you should implement this code in every Activity you are openning
Or your Activities are not opened?
Ok Sir, i will try. Thanks for your help. Pleasure to talk with you. Do u have facebook account?
http://www.facebook.com/beshkin
First thank you so much. Everyhing works real fine!
But my problem is now that i want that gesture only when i swipe over a special linear layout and not over the whole screen.
Can u help me?
Hi,
haven’t tried to do it for a single layout.
But this post looks what you need http://saga-androidapplication.blogspot.ie/2011/08/how-to-use-swipe-in-android.html
Hey thank you for this! It works brilliantly. However, if i want to detect motion event on a particular view, how do i do that?? Like i have two fragments, one on the left and the other on the right. I want to apply motion listener to the right fragment only. Any idea??
This question was raised before in the comments.
I haven’t tried to do it myself. So, if you will find any solution, tell us.
I know, that on every event can be set definite touch listener:
GestureDetector mGestureDetector = new GestureDetector(this, mGestureListener); element.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mGestureDetector.onTouchEvent(event); }mGestureDetector is a connector to listener:
/** * Gesture Event Handler */ private SimpleOnGestureListener mGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { Log.i(TAG, "[CALLBACK_GL] boolean onDown(e:" + e + ")"); return super.onDown(e); } @Override public boolean onSingleTapUp(MotionEvent e) { /** * * Do your stuff * */ return super.onSingleTapUp(e); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.i(TAG, "[CALLBACK_GL] boolean onSingleTapConfirmed(e:" + e + ")"); return super.onSingleTapConfirmed(e); } @Override public boolean onDoubleTap(MotionEvent e) { Log.i(TAG, "[CALLBACK_GL] boolean onDoubleTap(e:" + e + ")"); return super.onDoubleTap(e); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.i(TAG, "[CALLBACK_GL] boolean onFling(e1:" + e1 + ", e2:" + e2 + ", velocityX:" + velocityX + ", velocityY:" + velocityY + ""); return super.onFling(e1, e2, velocityX, velocityY); } @Override public void onShowPress(MotionEvent e) { Log.i(TAG, "[CALLBACK_GL] void onShowPress(e:" + e + ")"); super.onShowPress(e); } @Override public void onLongPress(MotionEvent e) { Log.i(TAG, "[CALLBACK_GL] void onLongPress(e:" + e + ")"); super.onLongPress(e); } };Thanks for your reply. I tried this but it doesn’t go into onFling. Only onDown, onShowPress and onLongPress is called. Something else needs to be done??
I made it work! You have to return true inside onDown() and it works! Thanks again! Here’s where i found it: http://thompsonng.blogspot.in/2011/07/android-simpleongesturelistener-not.html
I use your solution in combination with an ActionBar. But now i can’t select an OptionItem. What do I have to do for using swipe gestures and detecting a singleTap on an Option Item???
good tutorial.
but how to detect on which list item swipe event is performed.
I am getting error
Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘android.R.id.list’
I have a list View in .xml with id list.
still getting error. please give me a solution. thanks
check your project. if needed, make clean project from Eclipse menu
Sir, i have implemented your code. It works awesomely good but i want to apply it on my ImageView only. can you tell me how to do it? Please help!!!!!!!
Rohit, check my answer to Vikram.
It is possible to apply swipe gesture listener to any element.
I have to add only following method
imageView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event)
}
Remaining all will remain same na??
yes, should work.
its not working Sir. can u please help me with example?
Thank you for your code. It worked and reduced a lot of effort from me!
Thank you so much. So cool and worked without any prob.
[...] detail activity of the item to show the detail view of next item in the list. I am following this http://misha.beshkin.lv/android-swipe-gesture-implementation/ but when i swipe from left to right next view is not displaying just getting a toast message [...]
hi sir.. we are creating a java application that most likely story teller for our thesis.. but we are having a problem about swiping left and right from the 1st activity to another activity (from page 1 to page 2) how can i implement this codes.. please help us..
Hello,
I would help you with honor. But if it is commercial project, I would ask for some reward on my knowledge and help.
contact me for details.
Misha.
Hi, i get the next error:
06-25 17:36:26.229: E/AndroidRuntime(21264): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘android.R.id.list’
could u help me, please?
Hi,
you should add following line to ListView in your layout
android:id=”@id/android:list”
Would like to check with you, what parameter can be adjusted to set the sensitivity?
Many Thanks!
Check the following values:
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
you should play with them in order to adjust sensitivity
sorry but i just want to know what and where i need to put the code that when i swipe to left it will go to the next activty.. please..
you should add the following code:
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left"; startActivity(new Intent(this, NextActivity.class)); break;sorry but i just want to know what and where i need to put the code that when i swipe to left it will go to the next activity.. please..
Hi great Moishe,
I’ve implemented the swipe functionality ok but how do I prevent the user from swiping repeatedly? I’d like the swipe functionality to wait 1 second before it allows the gesture to be repeated.
I think it should be in the e2 < gesture code but have not seen an example yet.
thanks
hi,, i have a few questions :
1. what is mode used for??
2. what is the differences between 3 mode that exist in your code and what is it used for??
thx
the interface SimpleGestureListener should be public
Categories
Download Formula One app for Android.
Get your copy of Open F1 app in Google Play
Or use QR code reader

or from this site
Open Formula One app for Android
Or use QR code reader

Like this page on Facebook
Follow my twits
Popular Posts
Archives
Tags
Luach for Tallinn, Estonia
June 25, 2013
17 Tammuz 5773
© 2013 Moishe Beshkin | Techozoic 2.1.1 by Jeremy Clark. | Top
111 mySQL queries in 0.824 seconds.