Created
March 21, 2013 21:48
-
-
Save iBeacons/5217121 to your computer and use it in GitHub Desktop.
SwipeDetector
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
| package com.appcompetence.utils; | |
| import android.util.Log; | |
| import android.view.MotionEvent; | |
| import android.view.View; | |
| public class SwipeDetector implements View.OnTouchListener | |
| { | |
| static final String logTag = "ActivitySwipeDetector"; | |
| static final int MIN_DISTANCE = 100; | |
| private float downX, downY, upX, upY; | |
| private Callback callback; | |
| public static interface Callback | |
| { | |
| public void moveRight(); | |
| public void moveLeft(); | |
| public void moveUp(); | |
| public void moveDown(); | |
| public void onClick(); | |
| } | |
| public SwipeDetector(Callback callback) | |
| { | |
| this.callback = callback; | |
| } | |
| public void onRightToLeftSwipe() | |
| { | |
| callback.moveLeft(); | |
| } | |
| public void onLeftToRightSwipe() | |
| { | |
| callback.moveRight(); | |
| } | |
| public void onTopToBottomSwipe() | |
| { | |
| callback.moveDown(); | |
| } | |
| public void onBottomToTopSwipe() | |
| { | |
| callback.moveUp(); | |
| } | |
| public boolean onTouch(View v, MotionEvent event) | |
| { | |
| switch (event.getAction()) | |
| { | |
| case MotionEvent.ACTION_DOWN: | |
| { | |
| downX = event.getX(); | |
| downY = event.getY(); | |
| return true; | |
| } | |
| case MotionEvent.ACTION_UP: | |
| { | |
| upX = event.getX(); | |
| upY = event.getY(); | |
| float deltaX = downX - upX; | |
| float deltaY = downY - upY; | |
| // swipe horizontal? | |
| if (Math.abs(deltaX) > MIN_DISTANCE) | |
| { | |
| // left or right | |
| if (deltaX < 0) | |
| { | |
| this.onLeftToRightSwipe(); | |
| return true; | |
| } | |
| if (deltaX > 0) | |
| { | |
| this.onRightToLeftSwipe(); | |
| return true; | |
| } | |
| } | |
| else | |
| { | |
| Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); | |
| callback.onClick(); | |
| return false; // We don't consume the event | |
| } | |
| // swipe vertical? | |
| if (Math.abs(deltaY) > MIN_DISTANCE) | |
| { | |
| // top or down | |
| if (deltaY < 0) | |
| { | |
| this.onTopToBottomSwipe(); | |
| return true; | |
| } | |
| if (deltaY > 0) | |
| { | |
| this.onBottomToTopSwipe(); | |
| return true; | |
| } | |
| } | |
| else | |
| { | |
| Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); | |
| callback.onClick(); | |
| return false; // We don't consume the event | |
| } | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment