How to disable or enable viewpager swiping in android
Disable swipe progmatically by-
final View touchView = findViewById(R.id.Pager);
touchView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
and use this to swipe manually
touchView.setCurrentItem(int index);
In your custom view pager adapter, override those methods in ViewPager
.
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
And to enable, just return each super
method:
super.onInterceptTouchEvent(event)
and super.onTouchEvent(event)
.
Best solution for me. -First, you create a class like this:
public class CustomViewPager extends ViewPager {
private Boolean disable = false;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs){
super(context,attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return !disable && super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !disable && super.onTouchEvent(event);
}
public void disableScroll(Boolean disable){
//When disable = true not work the scroll and when disble = false work the scroll
this.disable = disable;
}
}
-Then change this in your layout:<android.support.v4.view.ViewPager
for this<com.mypackage.CustomViewPager
-Finally, you can disable it:view_pager.disableScroll(true);
or enable it: view_pager.disableScroll(false);
I hope that this help you :)