How to Detect the Swipe Left or Right in Android

How to detect the swipe left or Right in Android?

Simplest left to right swipe detector:

In your activity class add following attributes:

private float x1,x2;
static final int MIN_DISTANCE = 150;

and override onTouchEvent() method:

@Override
public boolean onTouchEvent(MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE)
{
Toast.makeText(this, "left2right swipe", Toast.LENGTH_SHORT).show ();
}
else
{
// consider as something else - a screen tap for example
}
break;
}
return super.onTouchEvent(event);
}

How to detect swipe direction between left/right and up/down

I wrote a simple class for this: it's well documented so I wont explain it here

public class OnSwipeListener extends GestureDetector.SimpleOnGestureListener {

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

// Grab two events located on the plane at e1=(x1, y1) and e2=(x2, y2)
// Let e1 be the initial event
// e2 can be located at 4 different positions, consider the following diagram
// (Assume that lines are separated by 90 degrees.)
//
//
// \ A /
// \ /
// D e1 B
// / \
// / C \
//
// So if (x2,y2) falls in region:
// A => it's an UP swipe
// B => it's a RIGHT swipe
// C => it's a DOWN swipe
// D => it's a LEFT swipe
//

float x1 = e1.getX();
float y1 = e1.getY();

float x2 = e2.getX();
float y2 = e2.getY();

Direction direction = getDirection(x1,y1,x2,y2);
return onSwipe(direction);
}

/** Override this method. The Direction enum will tell you how the user swiped. */
public boolean onSwipe(Direction direction){
return false;
}

/**
* Given two points in the plane p1=(x1, x2) and p2=(y1, y1), this method
* returns the direction that an arrow pointing from p1 to p2 would have.
* @param x1 the x position of the first point
* @param y1 the y position of the first point
* @param x2 the x position of the second point
* @param y2 the y position of the second point
* @return the direction
*/
public Direction getDirection(float x1, float y1, float x2, float y2){
double angle = getAngle(x1, y1, x2, y2);
return Direction.fromAngle(angle);
}

/**
*
* Finds the angle between two points in the plane (x1,y1) and (x2, y2)
* The angle is measured with 0/360 being the X-axis to the right, angles
* increase counter clockwise.
*
* @param x1 the x position of the first point
* @param y1 the y position of the first point
* @param x2 the x position of the second point
* @param y2 the y position of the second point
* @return the angle between two points
*/
public double getAngle(float x1, float y1, float x2, float y2) {

double rad = Math.atan2(y1-y2,x2-x1) + Math.PI;
return (rad*180/Math.PI + 180)%360;
}

public enum Direction{
up,
down,
left,
right;

/**
* Returns a direction given an angle.
* Directions are defined as follows:
*
* Up: [45, 135]
* Right: [0,45] and [315, 360]
* Down: [225, 315]
* Left: [135, 225]
*
* @param angle an angle from 0 to 360 - e
* @return the direction of an angle
*/
public static Direction fromAngle(double angle){
if(inRange(angle, 45, 135)){
return Direction.up;
}
else if(inRange(angle, 0,45) || inRange(angle, 315, 360)){
return Direction.right;
}
else if(inRange(angle, 225, 315)){
return Direction.down;
}
else{
return Direction.left;
}

}

/**
* @param angle an angle
* @param init the initial bound
* @param end the final bound
* @return returns true if the given angle is in the interval [init, end).
*/
private static boolean inRange(double angle, float init, float end){
return (angle >= init) && (angle < end);
}
}
}

To use simply extend the OnSwipeListener and override the onSwipe method

Android: How to handle right to left swipe gestures

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();
}

});

Detecting swipes, click, hold on one View Android

Gesture Detector is the way to go.

Alternatively,

 image.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {

switch (event.getAction()) {

case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
t1 = System.currentTimeMillis();
return true;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
t2 = System.currentTimeMillis();

if (x1 == x2 && y1 == y2 && (t2 - t1) < CLICK_DURATION) {
Toast.makeText(getActivity(), "Click", Toast.LENGTH_SHORT).show();
} else if ((t2 - t1) >= CLICK_DURATION) {
Toast.makeText(getActivity(), "Long click", Toast.LENGTH_SHORT).show();
} else if (x1 > x2) {
Toast.makeText(getActivity(), "Left swipe", Toast.LENGTH_SHORT).show();
} else if (x2 > x1) {
Toast.makeText(getActivity(), "Right swipe", Toast.LENGTH_SHORT).show();
}

return true;
}

return false;
}

Detecting left and right swipes on Fragment

I believe this line is wrong:

float diffX = e2.getX() - e2.getX();

should be

float diffX = e2.getX() - e1.getX();

Detect swipe direction on Jetpack Compose

Modifier.dragGestureFilter detects dragging in any direction. Pass an instance of DragObserver and override onDrag. Here you can detect the swipe direction based on the Offset. This object has x and y values, which are positive or negative based on the direction.

Here's what your code could look like:

Box(
Modifier.dragGestureFilter(
dragObserver = object : DragObserver() {
override fun onDrag(dragDistance: Offset): Offset {
val (x, y) = dragDistance
when {
x > 0 -> { /* right */ }
x < 0 -> { /* left */ }
}
when {
y > 0 -> { /* down */ }
y < 0 -> { /* up */ }
}
}
}
)
)

To actually move the object, you would have to apply Modifier.offset with values that are updated in onDrag.

Detect swipe gestures and touch events on a view

I found a solution.

In OnSwipeTouchListener.java:

public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

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

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public void onSwipeBottom() {
}

public void onSwipeTop() {
}

public void onDownTouch() {

}

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

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

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

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

@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_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}

}

And in activity:

To detect button release press: (on click)

public void timerButtonPressed(View view) {

}

To detect swipes and down press:

timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {

public void onSwipeLeft() {

}

public void onSwipeRight() {

}

public void onSwipeBottom() {

}

public void onSwipeTop() {

}

public void onDownTouch() {

}
});

Detect a finger swipe through JavaScript on the iPhone and Android

Simple vanilla JS code sample:

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;
var yDown = null;

function getTouches(evt) {
return evt.touches || // browser API
evt.originalEvent.touches; // jQuery
}

function handleTouchStart(evt) {
const firstTouch = getTouches(evt)[0];
xDown = firstTouch.clientX;
yDown = firstTouch.clientY;
};

function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}

var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;

var xDiff = xDown - xUp;
var yDiff = yDown - yUp;

if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* right swipe */
} else {
/* left swipe */
}
} else {
if ( yDiff > 0 ) {
/* down swipe */
} else {
/* up swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};

Tested in Android.

Android Right and Left Swipe Gestures handling

scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:{
downX = event.getX();}
case MotionEvent.ACTION_UP:{
upX = event.getX();

float deltaX = downX - upX;

if(Math.abs(deltaX)>0){
if(deltaX>=0){
swipeToRight();
return true;
}else{
swipeToLeft();
return true;
}
}
}
}

return false;
}
});


Related Topics



Leave a reply



Submit