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*/);
}
}
}
Then in your Layout.XML file replace any --- com.android.support.V4.ViewPager ---
tags with --- com.yourpackage.NonSwipeableViewPager --- tags.
Same solution but in Kotlin:
class NonSwipeableViewPager constructor(
context: Context,
attrs: AttributeSet?
) : ViewPager(context, attrs) {
private var isPagingEnabled = true
override fun onTouchEvent(event: MotionEvent?): Boolean {
return isPagingEnabled && super.onTouchEvent(event)
}
override fun onInterceptTouchEvent(event: MotionEvent?): Boolean {
return isPagingEnabled && super.onInterceptTouchEvent(event)
}
fun setPagingEnabled(isEnabled: Boolean) {
isPagingEnabled = isEnabled
}
}