ViewPager detect when user is trying to swipe out of bounds

后端 未结 5 1055
生来不讨喜
生来不讨喜 2020-11-27 04:05

I am using the ViewPager consisting of 6 pages to display some data. I want to be able to call a method when the user is at position 0 and tries to swipe to the right (backw

5条回答
  •  感动是毒
    2020-11-27 04:26

    I wonder how it worked for others, it's not working for me.

    onInterceptTouchEvent() only takes ACTION_DOWN event. While onTouchEvent() only takes one event at a time either ACTION_DOWN, ACTION_UP and others.

    I had to override both onInterceptTouchEvent() and onTouchEvent() to make it work properly. The ACTION_DOWN of onInterceptTouchEvent grabs initial X point of touch, and OnTouchEvent grabs final X2 point. Which I compared it to detect swipe direction.

    Get initial X value of the touch:

    float x1 = 0;
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
            switch(ev.getAction() & MotionEventCompat.ACTION_MASK){
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            }
            return super.onInterceptTouchEvent(ev);
        }
    

    From tjlian616's code, the onTouchEvent() listens to ACTION_UP and gets it's last X Value. While I've set my current item's value to be 0 to get swipe out at start listener. Compared it and add fired up the listener.

     @Override
     public boolean onTouchEvent(MotionEvent ev){
            if(getCurrentItem()==0){
                final int action = ev.getAction();
                switch(action & MotionEventCompat.ACTION_MASK){
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    mStartDragX = ev.getX();
                    if (x1

提交回复
热议问题