Created
June 17, 2020 04:45
-
-
Save nguyenlinhnttu/bc591e545709be9d6c25698e8bda48f2 to your computer and use it in GitHub Desktop.
SwipeView detect swipe left, right, top, bottom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.view.MotionEvent; | |
import android.view.View; | |
import android.widget.RelativeLayout; | |
/** | |
* Created by NguyenLinh on 17,June,2020 | |
*/ | |
public class SwipeView extends RelativeLayout implements View.OnTouchListener { | |
private SwipeCallback swipeCallback; | |
private SwipeDirection detectSwipeDirection; | |
float x1, x2, y1, y2; | |
public SwipeView(Context context) { | |
super(context); | |
} | |
public SwipeView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public SwipeView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
} | |
public SwipeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { | |
super(context, attrs, defStyleAttr, defStyleRes); | |
} | |
public void detectLeft(SwipeCallback swipeCallback) { | |
this.swipeCallback = swipeCallback; | |
detectSwipeDirection = SwipeDirection.LEFT; | |
} | |
@Override | |
public boolean onInterceptTouchEvent(MotionEvent event) { | |
switch (event.getAction()) { | |
case MotionEvent.ACTION_DOWN: | |
x1 = event.getX(); | |
y1 = event.getY(); | |
break; | |
case MotionEvent.ACTION_UP: | |
x2 = event.getX(); | |
y2 = event.getY(); | |
SwipeDirection direction = null; | |
float xDiff = x2 - x1; | |
float yDiff = y2 - y1; | |
if (Math.abs(xDiff) > Math.abs(yDiff)) { | |
if (x1 < x2) { | |
direction = SwipeDirection.RIGHT; | |
} else { | |
direction = SwipeDirection.LEFT; | |
} | |
} | |
if (detectSwipeDirection != null) { | |
if (direction == SwipeDirection.RIGHT) { | |
swipeCallback.onSwipeRight(); | |
} | |
if (direction == SwipeDirection.LEFT) { | |
swipeCallback.onSwipeLeft(); | |
} | |
if ( direction == SwipeDirection.TOP ){ | |
swipeCallback.onSwipeTop(); | |
} | |
if ( direction == SwipeDirection.BOTTOM ){ | |
swipeCallback.onSwipeBottom(); | |
} | |
} | |
break; | |
} | |
return false; | |
} | |
@Override | |
public boolean onTouch(View view, MotionEvent event) { | |
return super.onTouchEvent(event); | |
} | |
public enum SwipeDirection { | |
TOP, RIGHT, BOTTOM, LEFT | |
} | |
public interface SwipeCallback { | |
default void onSwipeTop(){} | |
default void onSwipeRight(){} | |
default void onSwipeBottom(){} | |
default void onSwipeLeft(){} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment