LoginSignup
2

More than 5 years have passed since last update.

ViewPagerのスワイプを抑止する方法

Posted at

こんなクラスを使う。

キモは、onTouchEventonInterceptTouchEventの両メソッドをオーバーライドしてタッチイベントを奪ってしまうこと

public class SwipeControlViewPager extends ViewPager {

    protected boolean enableSwipe = true;

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

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

    public void setSwipeEnable(boolean enable) {
        this.enableSwipe = enable;
    }

    public void toggleSwipeEnable() {
        this.enableSwipe = !this.enableSwipe;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (enableSwipe) {
            return super.onInterceptTouchEvent(ev);
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (enableSwipe) {
            return super.onTouchEvent(ev);
        }
        return false;
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2