3

I am using a viewpager in Android und would like to control which way the user can swipe the page.

I am using this code to detect the direction of the swipe:

// Detects the direction of swipe. Right or left. 
// Returns true if swipe is in right direction
public boolean detectSwipeToRight(MotionEvent event){

 int initialXValue = 0; // as we have to detect swipe to right
 final int SWIPE_THRESHOLD = 100; // detect swipe
 boolean result = false;

        try {                
            float diffX = event.getX() - initialXValue;

                if (Math.abs(diffX) > SWIPE_THRESHOLD ) {
                    if (diffX > 0) {

                        // swipe from left to right detected ie.SwipeRight
                        result = false;
                    } else {

                        Log.e("swipeToLeft", "swipeToLeft");
                        result = true;
                    }
                }
            } 
         catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }

This code however always returns "false". What changes must be made in the code work it to work properly?

deimos1988
  • 5,896
  • 7
  • 41
  • 57

1 Answers1

1

It seems right that your code always return false considering that you always initialize your starting point at 0

int initialXValue = 0;

I think that you have to detect the starting point of the swipe action and not only manage the event referred to your ending point.

You have to consider two different variables.

int downX; //initialized at the start of the swipe action
int upX; //initialized at the end of the swipe action

buttonIcons.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(final View v, final MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();

                return true;

            case MotionEvent.ACTION_UP:

                upX = event.getX();
                final float deltaX = downX - upX;

                if (deltaX > 0 && deltaX > SWIPE_MIN_DISTANCE) {

                  //DETECTED SWIPE TO RIGHT

                }
                if (deltaX < 0 && -deltaX > SWIPE_MIN_DISTANCE) {

                   //DETECTED SWIPE TO LEFT

                }
                return true;

            }

            return false;
        }
    });
}
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
axl coder
  • 739
  • 3
  • 19
  • but what is the value of SWIPE_MIN_DISTANCE? – Shailesh Jul 14 '17 at 06:02
  • SWIPE_MIN_DISTANCE is the threshold that you decide is necessary to detect an effective swipe (and not just a touch). In the original question for example deimos1988 used a variable named SWIPE_THRESHOLD with a value of 100. – axl coder Jul 24 '17 at 12:07