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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rahul Baboria
Rahul Baboria is having good knowledge over Android Application.