---
title: "最靠谱的禁止ViewPager滑动方法"
author: "Darar"
date: "2013-05-15T14:44:12Z"
tags: []
categories: ["移动开发"]
slug: "viewpager"
draft: false
lastmod: "2013-05-15T14:44:12Z"
id: 1869757
url: "https://darar.iteye.com/blog/1869757"
---

最近做项目要求某种情况下ViewPager不能滑动，在网上找了一圈。有说重写Ontouch的，各种。都试了试，基本都不可用。

自己看ViewPager源码，知道VIewPager移动全部都调用了scrollTo方法，这个是View的方法，那么我们只需要重写这个方法就可以禁止ViewPager滑动


```java
public class CustomViewPager extends ViewPager {

    private boolean isCanScroll = true;

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScanScroll(boolean isCanScroll){
        this.isCanScroll = isCanScroll;
    }


    @Override
    public void scrollTo(int x, int y){
        if (isCanScroll){
            super.scrollTo(x, y);
        }
    }


```