最靠譜的禁止ViewPager滑動方法

最近作項目要求某種狀況下ViewPager不能滑動,在網上找了一圈。有說重寫Ontouch的,各類。都試了試,基本都不可用。 

本身看ViewPager源碼,知道VIewPager移動所有都調用了scrollTo方法,這個是View的方法,那麼咱們只須要重寫這個方法就能夠禁止ViewPager滑動 

ide

Java代碼this

  1. public class CustomViewPager extends ViewPager {  spa

  2.   

  3.     private boolean isCanScroll = true;  源碼

  4.   

  5.     public CustomViewPager(Context context) {  class

  6.         super(context);  List

  7.     }  scroll

  8.   

  9.     public CustomViewPager(Context context, AttributeSet attrs) {  方法

  10.         super(context, attrs);  項目

  11.     }  touch

  12.   

  13.     public void setScanScroll(boolean isCanScroll){  

  14.         this.isCanScroll = isCanScroll;  

  15.     }  

  16.   

  17.   

  18.     @Override  

  19.     public void scrollTo(int x, int y){  

  20.         if (isCanScroll){  

  21.             super.scrollTo(x, y);  

  22.         }  

  23.     }  

此時,ViewPager.setCurretItem方法也會失效,想經過點擊Tab button 切換page也沒法實現。

2、setOnTouchListener

ViewPager.setOnTouchListener(new View.OnTouchListener(){

        on touch ( xx ){

                return true;

        }

});

這種方式能夠實現只禁止滑動翻頁,能夠經過setCurrentItem,來切換頁面。

相關文章
相關標籤/搜索