AndroidViewPager prohibits left swipe (right swipe)

 

 

 

package com.xba.nwwdpro.makenna.utils;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Create Author: Makenna
 * Create Date: 2016/4/27 15:48
 * Create Function:
 */
public class CanotSlidingViewpager extends ViewPager {
    private float beforeX;//The last x coordinate
    private boolean isCanScroll = true;//Set whether it can be swiped

    public CanotSlidingViewpager(Context context) {
        super(context);
    }

    public CanotSlidingViewpager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    //------------Swipe left and right is prohibited-------------------
//    @Override
//    public boolean onTouchEvent(MotionEvent ev) {
//        if (isCanScroll) {
//            return super.onTouchEvent(ev);
//        } else {
//            return false;
//        }
//
//    }
//
//    @Override
//    public boolean onInterceptTouchEvent(MotionEvent arg0) {
//        // TODO Auto-generated method stub
//        if (isCanScroll) {
//            return super.onInterceptTouchEvent(arg0);
//        } else {
//            return false;
//        }
//
//    }
    //-----Left swipe prohibited ------- Left swipe: last coordinate > current coordinate
    //if (motionValue > 0)
    //-----Right swipe prohibited -------Right swipe: last coordinate < current coordinate
    //if (motionValue < 0)
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isCanScroll) {
            return super.dispatchTouchEvent(ev);
        } else {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN://press if 'only' as the 'last coordinate', it is not appropriate, because there may be left sliding, the motionValue is greater than 0 (sliding back and forth, as long as the stop coordinate is on the right side of the pressed coordinate, left sliding still slide over)
                    beforeX = ev.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float motionValue = ev.getX() - beforeX;
                    if (motionValue > 0) {//Disable right swipe
                        return true;
                    }
                    beforeX = ev.getX();//When the finger moves, use the current coordinates as the next 'last coordinates' to solve the above problems

                    break;
                default:
                    break;
            }
            return super.dispatchTouchEvent(ev);
        }
    }

    /**
     * Set whether to swipe
     *
     * @param isCanScroll
     */
    public void setScrollble(boolean isCanScroll) {
        this.isCanScroll = isCanScroll;
    }

    public boolean isScrollble() {
        return isCanScroll;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326847341&siteId=291194637
Recommended