Search code examples
androidandroid-viewpagerswipe

detect when user swipes the viewpager from edge of a page


I am sure that there are some posts about it, and I skimmed through them before, but now I cannot find them.

I want to detect the action when the user swipes the viewpager from edge of a page (such as left edge). I want to do some special handling for this kind of swipe, such as showing menu.

Is there any ViewPager built-in(?) support for it? I vaguely remembered it is. Otherwise, I have to implement my own logic to detect those action.

Can anyone point me some info?

enter image description here


Solution

  • I think, you should override few methods of the container of your ViewPager. For example if it is LinearLayout

    public class Liner extends LinearLayout {
    
    public Liner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }
    
    //Remember start points
    float mInitX;
    float mInitY;
    // TouchSlop value
    float mSomeValue=20F;
    // 
    boolean mCatched=false;
    
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
    
        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mInitX=ev.getX();
            mInitY=ev.getY();
            break;
    
        default:
            break;
        }
    
        mCatched=mInitX<10 && Math.abs(ev.getX()-mInitX)>mSomeValue;
    
        return mCatched;
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mCatched){
            //Do all you want here
        }
        return true;
    }
    

    }

    If you combine with TeRRo anrwer (put his detector inside onTouchEvent()) you may have good result. But best way to use DrawerLayout.

    Good luck!