How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

时间:2023-11-24 19:48:20

The more general extension of ViewPager would bet to create a "SetPagingEnabled" method so that we can enable and disable paging on the fly. To enable / disable the swiping, just overide two methods: "onTouchEvent" and "onInterceptTouchEvent". Both will return "false" if the paging was disabled.

public class CustomViewPager extends ViewPager {

private boolean enabled;

public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
} @Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
} return false;
} @Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
} return false;
} public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
} }

Then select this instead of the builtin viewpager in XML

<mypackage.CustomViewPager
android:id="@+id/myViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />

You just need to call the "setPagingEnabled" method with "false" and users won't be able to swipe to paginate

http://*.com/questions/9650265/how-do-disable-paging-by-swiping-with-finger-in-viewpager-but-still-be-able-to-s