Stop Swipe Action in Android Viewpager

Posted By : Rahul Baboria | 29-Oct-2017

Introduction:

Viewpager in android allows user to flip right and left to see next and previous pages. It can further work with tabs as we can see in too many android applications such as facebook,whatsapp , etc when user swipes , it to another page . But there are some designs where we don't want user to flip page via touch on pages but by pressing tabs , at this point we have to stop default action of viewpager by customizing its default methods of scrolling.

 

To create a viewpager without default swipe action . We have to stop the swipe actions. You can use following code to create class for NonSwipable ViewPager.

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

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

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // stop swipe 
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // stop switching pages
        return false;
    }

    private void setMyScroller() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyScroller extends Scroller {
        public MyScroller(Context context) {
            super(context, new DecelerateInterpolator());
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
        }
    }
}

Pros:

1. Default flipping of page will be barred.

2. User can switch between pages using tab layout.

3. Can build Complex designs such as opening dialogs, or disable particular tab.

4. No more customisation needed.

 

Thanks.

 

 

About Author

Author Image
Rahul Baboria

Rahul Baboria is having good knowledge over Android Application.

Request for Proposal

Name is required

Comment is required

Sending message..