Android: How to handle right to left swipe gestures

458,088

Solution 1

OnSwipeTouchListener.java:

import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                }
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

Usage:

imageView.setOnTouchListener(new OnSwipeTouchListener(MyActivity.this) {
    public void onSwipeTop() {
        Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeRight() {
        Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeLeft() {
        Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeBottom() {
        Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
    }

});

Solution 2

This code detects left and right swipes, avoids deprecated API calls, and has other miscellaneous improvements over earlier answers.

/**
 * Detects left and right swipes across a view.
 */
public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context context) {
        gestureDetector = new GestureDetector(context, new GestureListener());
    }

    public void onSwipeLeft() {
    }

    public void onSwipeRight() {
    }

    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_DISTANCE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float distanceX = e2.getX() - e1.getX();
            float distanceY = e2.getY() - e1.getY();
            if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceX > 0)
                    onSwipeRight();
                else
                    onSwipeLeft();
                return true;
            }
            return false;
        }
    }
}

Use it like this:

view.setOnTouchListener(new OnSwipeTouchListener(context) {
    @Override
    public void onSwipeLeft() {
        // Whatever
    }
});

Solution 3

If you also need to process click events here some modifications:

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());

    public boolean onTouch(final View v, final MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            result = onSwipeRight();
                        } else {
                            result = onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            result = onSwipeBottom();
                        } else {
                            result = onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public boolean onSwipeRight() {
        return false;
    }

    public boolean onSwipeLeft() {
        return false;
    }

    public boolean onSwipeTop() {
        return false;
    }

    public boolean onSwipeBottom() {
        return false;
    }
}

And sample usage:

    background.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            toggleSomething();
        }
    });
    background.setOnTouchListener(new OnSwipeTouchListener() {
        public boolean onSwipeTop() {
            Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeRight() {
            Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeLeft() {
            Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
            return true;
        }
        public boolean onSwipeBottom() {
            Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

Solution 4

Expanding on Mirek's answer, for the case when you want to use the swipe gestures inside a scroll view. By default the touch listener for the scroll view get disabled and therefore scroll action does not happen. In order to fix this you need to override the dispatchTouchEvent method of the Activity and return the inherited version of this method after you're done with your own listener.

In order to do a few modifications to Mirek's code: I add a getter for the gestureDetector in the OnSwipeTouchListener.

public GestureDetector getGestureDetector(){
    return  gestureDetector;
}

Declare the OnSwipeTouchListener inside the Activity as a class-wide field.

OnSwipeTouchListener onSwipeTouchListener;

Modify the usage code accordingly:

onSwipeTouchListener = new OnSwipeTouchListener(MyActivity.this) {
    public void onSwipeTop() {
        Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeRight() {
        Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeLeft() {
        Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeBottom() {
        Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
    }
});

imageView.setOnTouchListener(onSwipeTouchListener);

And override the dispatchTouchEvent method inside Activity:

@Override
    public boolean dispatchTouchEvent(MotionEvent ev){
        swipeListener.getGestureDetector().onTouchEvent(ev); 
            return super.dispatchTouchEvent(ev);   
    }

Now both scroll and swipe actions should work.

Solution 5

In order to have Click Listener, DoubleClick Listener, OnLongPress Listener, Swipe Left, Swipe Right, Swipe Up, Swipe Down on Single View you need to setOnTouchListener. i.e,

view.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

            @Override
            public void onClick() {
                super.onClick();
                // your on click here
            }

            @Override
            public void onDoubleClick() {
                super.onDoubleClick();
                // your on onDoubleClick here
            }

            @Override
            public void onLongClick() {
                super.onLongClick();
                // your on onLongClick here
            }

            @Override
            public void onSwipeUp() {
                super.onSwipeUp();
                // your swipe up here
            }

            @Override
            public void onSwipeDown() {
                super.onSwipeDown();
                // your swipe down here.
            }

            @Override
            public void onSwipeLeft() {
                super.onSwipeLeft();
                // your swipe left here.
            }

            @Override
            public void onSwipeRight() {
                super.onSwipeRight();
                // your swipe right here.
            }
        });

}

For this you need OnSwipeTouchListener class that implements OnTouchListener.

public class OnSwipeTouchListener implements View.OnTouchListener {

private GestureDetector gestureDetector;

public OnSwipeTouchListener(Context c) {
    gestureDetector = new GestureDetector(c, new GestureListener());
}

public boolean onTouch(final View view, final MotionEvent motionEvent) {
    return gestureDetector.onTouchEvent(motionEvent);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        onClick();
        return super.onSingleTapUp(e);
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        onDoubleClick();
        return super.onDoubleTap(e);
    }

    @Override
    public void onLongPress(MotionEvent e) {
        onLongClick();
        super.onLongPress(e);
    }

    // Determines the fling velocity and then fires the appropriate swipe event accordingly
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                }
            } else {
                if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeDown();
                    } else {
                        onSwipeUp();
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}

public void onSwipeUp() {
}

public void onSwipeDown() {
}

public void onClick() {

}

public void onDoubleClick() {

}

public void onLongClick() {

}
}
Share:
458,088
endryha
Author by

endryha

Updated on June 05, 2021

Comments

  • endryha
    endryha about 3 years

    I want my app to recognize when a user swipes from right to left on the phone screen.

    How to do this?

  • clusterflux
    clusterflux over 11 years
    Needs some minor updates. Variables are mismatched in the onTouch method, and exception class is not imported. Would make more sense to just return false from onFling(), instead of initiating a variable, assigning it a value, doing nothing with it, and just returning it. Some parts of onTouch method are incorrect. See stackoverflow.com/questions/14107293/… One helpful tip that would've saved me some time and I hope may help others: when you use this method, you only want to add the "implements" tag to your OnSwipeTouchListener class
  • Opiatefuchs
    Opiatefuchs about 11 years
    works great, but super.onTouch(view, motionEvent); gives me error warning in eclipse "is undefinied for the type object". Deleting this works great.
  • Hugo Alves
    Hugo Alves over 10 years
    Thanks works like a charm but you should add a constructor to OnSwipeTouchListener that receives a context because that constructor of GestureDetector is deprecated since API level 3, and instantiate the GestureDetectorin that constructor.
  • Manny265
    Manny265 over 10 years
    this is in the main activity right? and then the list itself how do I load that? my main extends listactivity?
  • Nicolas Zozol
    Nicolas Zozol over 10 years
    I don't see easily the modifications in your modified OnSwipeTouchListener. Where is it exactly ?
  • hpique
    hpique over 10 years
    Shouldn't the THRESHOLD be expressed in dp?
  • Libathos
    Libathos over 10 years
    @Mirek Rusin Hi great code! can you telle me how can I use this code inside a viewPager? in order to recognize if i get a swipe from left to right
  • Hesam
    Hesam over 10 years
    public GestureDetector getGestureDetector() {return gestureDetector;} method should be add to the OnSwipeTouchListener class and be used inside onTouch() method.
  • Aneez
    Aneez over 10 years
    This thing worked for me. Now Can u please tell me how to give different actions(or simply toast) for right side vertical swipe and left side vertical swipe ?
  • Arash
    Arash about 10 years
    thanks it worked for me with these modifications : stackoverflow.com/a/19506010/401403
  • RicNjesh
    RicNjesh about 10 years
    How do you get a touch event for a listview item?
  • mangusta
    mangusta about 10 years
    but "onDown" is never called. as a consequence, my e1 is always null and I can do nothing about it.
  • mangusta
    mangusta about 10 years
    onDown() is never called, so I can't intercept null value of e1 and it remains null, so swipe never works
  • Jona
    Jona about 10 years
    sorry if this sounds thick, but (A) Where does the second piece of code go? (view.setOn...), (B) what is the "context" that is being passed? I'm quite new, appreciate any help! Thanks in advance
  • Edward Brey
    Edward Brey about 10 years
    @mangusta I'm not sure what you're seeing. onDown should be called with e (not e1) if the user moves vertically, but since this code snippet is for left-right swiping, it tells Android to ignore the vertical movement.
  • Edward Brey
    Edward Brey about 10 years
    @Jona You'll definitely want to get a good book or other resource on Android fundamentals; otherwise, trying to cobble solutions together from StackOverflow will prove frustrating. A good option is the official Training for Android developers. The section Starting an Activity tells about where you would put setOnTouchListener (typically in onCreate). context is the this pointer (unless you're creating a fragment).
  • Jona
    Jona about 10 years
    thank you Edward - I'm doing both simultaneously! (cobbling and reading)
  • Lara
    Lara almost 10 years
    It works great for swipes, thanx. My problem is that I still want to receive the onTouchEvent when there is no swipe. Can't figure that one out.
  • Edward Brey
    Edward Brey almost 10 years
    @Lara, I haven't tried this, but you could try overriding SimpleOnGestureListener.onSingleTapConfirmed.
  • Lara
    Lara almost 10 years
    Thanks, Edward. I also found that changing the return of onDown from true to false does the trick.
  • Jessica
    Jessica almost 10 years
    @Mirek Rusin What will happen if I change private static final int SWIPE_THRESHOLD to private final int SWIPE_THRESHOLD ?! I need to set swipe sensitivity in run time !!!
  • Figen Güngör
    Figen Güngör almost 10 years
    When I add code to touch event and tried to swipe, touch event occurs, too. How can I avoid that?
  • Gábor
    Gábor over 9 years
    This should be the accepted answer... Differences are subtle but very important. First, there is no onDown(). Second, the handlers return a boolean to signal whether they consumed the event or not. This is of utmost importance if you need more than just one handler for the same view (which should be the default case, anyway).
  • LS_
    LS_ over 9 years
    i get error on the context here here: view.setOnTouchListener(new OnSwipeTouchListener(context) how can I solve it?
  • Edward Brey
    Edward Brey over 9 years
    @Signo, the activity containing the view provides context. In the common case of adding the view to a fragment, use Fragment.getActivity().
  • Ge Rong
    Ge Rong over 9 years
    My fix for this answer is to move onTouch into the OnSwipeTouchListener definition, otherwise my IDE will pop up "accessing private member" error
  • tung
    tung over 9 years
    What's that toggleSomething() Method?
  • ruX
    ruX over 9 years
    @tung just normal tap(not gesture) handler
  • ruX
    ruX over 9 years
    @NicolasZozol java code style, all swipe directions, on click handler
  • tung
    tung over 9 years
    Note for the View you wanna attach it has to be focusable and clickable
  • coderVishal
    coderVishal over 9 years
    has anybody extended the code to detect top and down swipes?
  • Edward Brey
    Edward Brey over 9 years
    @coderVishal Depending on your purpose, you may find useful SwipeRefreshLayout, the SwipeRefreshLayoutBasic sample, or one of its variants.
  • Neil
    Neil about 9 years
    @ruX "Thanks but in this case not initialized object can be root of NPE errors It's always safer to assign something not null to callback instance" The final modifier guarantees gestureDetector will always be initialized, and if not caught by the compiler. The edit I suggested to update to non-deprecated API is perfectly safe.
  • Alaa M.
    Alaa M. almost 9 years
    This is great, but when I attached it to a listView.setOnTouchListener(), it slowed down the scrolling (even though I was using a ViewHolderand some other optimizations.) To solve this, just don't call onSwipeBottom() and onSwipeTop() and make result = false on those cases. By "slowing down" I mean scrolling (smooth) and then stopping all at once - instead of stopping at a decreasing speed
  • serv-inc
    serv-inc almost 9 years
    How do you handle the android lint warning about ClickableViewAccessibility? (If you know a way, please post at my SO question at stackoverflow.com/questions/31344451/…)
  • Edward Falk
    Edward Falk almost 9 years
    Isn't this a copy of Thomas Fankhauser's answer? Credit where credit is due, please.
  • anubhav16
    anubhav16 almost 9 years
    I'm new to Android. I tried this code. Did not work. Application crashed with Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnTouchListener(android.view.Vie‌​w$OnTouchListener)' on a null object reference Where to write Usage Code?
  • Jennifer
    Jennifer almost 9 years
    Zala's solution is simple and clear, helped me greatly with swipe actions in android. This solution will solve beginners who have trouble with swipe gestures.
  • Awadesh
    Awadesh over 8 years
    please tell me how to swipe smoothly even user swipe somewhat in downward manner , right now I am also using android.support.v4.widget.SwipeRefreshLayout ,when i swipe in some zigzag manner both refresh and swipe try to take place
  • Awadesh
    Awadesh over 8 years
    listview item is not sliding smoothly I mean if user swipe slightly downward then swipe action is not detected. Any help is appreciated. Thanks in advance
  • Pravinsingh Waghela
    Pravinsingh Waghela over 8 years
    Plus one from my side, its very useful and the Tutorial link given by you is also very Interesting. Thanks for double help Edward.
  • tomDev
    tomDev over 8 years
    Thanks, this works, but I have some issues with this code. When gesture starts over a button it is not detected. Any idea why?
  • Edward Brey
    Edward Brey over 8 years
    @tomDev Likely it's because the button is handling the events, leaving nothing for the touch listener underneath. However, you should consider whether you really want a button on a control that supports swiping. The typical UI for such situations is for the swipe action to reveal buttons "behind" the list item. The class above doesn't support those buttons, but there are libraries available that do.
  • tomDev
    tomDev over 8 years
    @EdwardBreyYes, that's whats is happening. When the gesture starts over a button, the button is clicked and the gesture is not detected. On iOS it's the opposite, the gesture has the "priority". What other libraries can be used? No code needed, just some directions. Thanks!
  • Mohammad Rajob
    Mohammad Rajob over 8 years
    How can I use this in OnItemClickListener for listview?
  • TejaDroid
    TejaDroid about 8 years
    @Jaydipsinh Zala, You save my time, amazing. this will solve my problem of indicator of scroll top and bottom while scrolling.
  • Ajit Sharma
    Ajit Sharma about 8 years
    Its working nice but how to give color change effect while swipe?
  • Singagirl
    Singagirl almost 8 years
    Should I disregard Eclipse's warning OnSwipeTouchListener#onTouch should call View#performClick when a click is detected?
  • Edward Brey
    Edward Brey almost 8 years
    @DmitriyR I think so. I don't get that warning in Android Studio.
  • shobhan
    shobhan over 7 years
    How to restrict the user in down swipe i.e swipe bottom in your case , I want to disable down swipe in my case . please let me know
  • soshial
    soshial over 7 years
    @AlaaM., how did you make scrolling in a ListView work?
  • soshial
    soshial over 7 years
    I switched from ListView to RecyclerView and it helped!
  • vijay chhalotre
    vijay chhalotre almost 7 years
    how to get there is not more item both side (left and right) ... please guide me on this. I need to enable and disable the arrow indicator. Thanks
  • Andrêves Dickow
    Andrêves Dickow over 6 years
    does anyone know how to call this 'Usage' in MainActivity on Xamarin.Android?
  • baldraider
    baldraider over 6 years
    Getting this error JNI DETECTED ERROR IN APPLICATION: JNI CallVoidMethodV called with pending exception java.lang.NullPointerException: Attempt to invoke virtual method 'float android.view.MotionEvent.getX()' on a null object reference why this error is thrown?
  • user3561494
    user3561494 over 6 years
    Can someone please show me an example of how to use Kotlin to detect both left swipe's and a normal click on the same view.
  • user3561494
    user3561494 over 6 years
    How do you use this in a list view? It does not return the position of the view that was touched so how do you know which row was touched?
  • Nathan F.
    Nathan F. about 6 years
    It might make more sense to make the OnSwipeTouchListener class abstract as well as the onSwipe* functions.
  • kamal
    kamal about 6 years
    For Kotlin You can use something like this:
  • kamal
    kamal about 6 years
    Usage:gv_calendar!!.setOnTouchListener(OnSwipeTouchListener(‌​activity,onSwipeCall‌​Back!!))
  • Mark Rotteveel
    Mark Rotteveel about 6 years
    Please don't just dump code, include an explanation of what your code does.
  • Hitesh Danidhariya
    Hitesh Danidhariya almost 6 years
    Can I do something like , if I swipe half the screen then on swipeDown() function is called or I get value to when swipe if done half the screen.
  • loshkin
    loshkin almost 6 years
    what is OnSwipeCallBack?
  • Soon Santos
    Soon Santos almost 6 years
    This is what I call a complete answer. When I added the swipes, I lost my click properties, so I needed to override the onClick method as in this answer. Thanks guy!
  • hiddeneyes02
    hiddeneyes02 almost 6 years
    Can you add rtl support please? That is onSwipeRight() and onSwipeLeft() get switched when rtl
  • Michał Ziobro
    Michał Ziobro almost 6 years
    I am getting NullPointerException on Orientation Changes while used in Fragment
  • JPM
    JPM almost 6 years
    Gesture comes from what import? import android.gesture.Gesture does not have a SWIPE_RIGHT global.
  • Arnold Brown
    Arnold Brown over 5 years
    Its working well, but have a doubt that the onClick is not working for the view the swipe is applied.! @Meric
  • Anonymous-E
    Anonymous-E over 5 years
    why you did not write down the complete code of this gesture, where to put SwipeDown, left, right etc?
  • Starwave
    Starwave over 5 years
    sifted through all the garbage here, you are right, no need for over-complicating things - this one works perfectly
  • Starwave
    Starwave over 5 years
    a giant minus here - if I do a gesture anywhere on my scrollview, the touchListener is called, even if it wasn't applied to the scrollview itself, but to a random button inside it
  • MHSFisher
    MHSFisher over 5 years
    Kotlin equivalent is here : stackoverflow.com/a/53791260/2201814
  • luckybilly
    luckybilly almost 5 years
    There are many SwipeConsumers for different sideslip effects, such as SlidingConsumer/StretchConsumer/SpaceConsumer/... and so on within SmartSwipe
  • Gerrit Beuze
    Gerrit Beuze over 4 years
    Should VELOCITY_THRESHOLD not be screen density dependent?
  • M D P
    M D P over 4 years
    @GerritBeuze No, Android system handles that. It sends the right values through velocityX and velocityY in onFling method. although you can experiment to see which value best suits your needs but the final number would be universal.
  • Gerrit Beuze
    Gerrit Beuze over 4 years
    The answers here suppose the opposite: they are not scaled ? : stackoverflow.com/questions/18812479/…
  • M D P
    M D P over 4 years
    @GerritBeuze It's because they are doing the math manually themselves by calculating the amount of pixels the finger has traveled and that's wrong because it depends on pixel density. you should only use velocity like I did, velocity is almost dpi independent.
  • Dinith Rukshan Kumara
    Dinith Rukshan Kumara over 4 years
    Greate answer. Works fine, but SwipeRight and onSwipeLeft directions should change. Swap it.
  • AL̲̳I
    AL̲̳I over 4 years
    @Jaydipsinh Zala Not sure what am I doing wrong, when I add the OnSwipeTouchListener to my webView, it removes the interaction with the website inside webview. Can you help please?
  • Faizan Haidar Khan
    Faizan Haidar Khan about 4 years
    Can we decrease the sensitivity? If yes then how?
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy almost 4 years
    Why we need to make the class open ??
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy almost 4 years
    Can we also detect tap gesture ?
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy almost 4 years
    In kotlin, we can replace Math.abs with abs() function
  • Amr
    Amr about 3 years
    giving a complete sample on how to use the code would have been great!
  • ThomasRS
    ThomasRS about 3 years
    Added missing class and exaple
  • Vitaly
    Vitaly over 2 years
    NullPointerException: Attempt to invoke virtual method 'float android.view.MotionEvent.getX()' on a null object reference
  • Dexter Legaspi
    Dexter Legaspi about 2 years
    this library was hosted in jcenter/bintray so since jcenter/bintray is no longer available to public since 2021, no bueno on this library.
  • Benjamin Basmaci
    Benjamin Basmaci about 2 years
    I don't quite see the use for abstraction here. Doesn't it just mandate that any inheriting class override every function? Meaning onSwipeLeft, onSwipeBottom etc. I'd say sometimes that is not necessary and only makes your code ugly.
  • Benjamin Basmaci
    Benjamin Basmaci about 2 years
    From your own source: "This is the kind of processing you would have to do for a custom gesture. However, if your app uses common gestures such as double tap, long press, fling, and so on, you can take advantage of the GestureDetector class." So I would guess that the accepted approach might be right here. Not sure how these MotionEvent ACTIONS are supposed to work. Because while they look like they might are defined as complete gestures, the paragraph I just posted and the Doc suggests otherwise. Didnt test it though. So maybe some extra explanation would help.