最近作項目要求某種狀況下ViewPager不能滑動,在網上找了一圈。有說重寫Ontouch的,各類。都試了試,基本都不可用。
本身看ViewPager源碼,知道VIewPager移動所有都調用了scrollTo方法,這個是View的方法,那麼咱們只須要重寫這個方法就能夠禁止ViewPager滑動
ide
Java代碼this
public class CustomViewPager extends ViewPager { spa
private boolean isCanScroll = true; 源碼
public CustomViewPager(Context context) { class
super(context); List
} scroll
public CustomViewPager(Context context, AttributeSet attrs) { 方法
super(context, attrs); 項目
} touch
public void setScanScroll(boolean isCanScroll){
this.isCanScroll = isCanScroll;
}
@Override
public void scrollTo(int x, int y){
if (isCanScroll){
super.scrollTo(x, y);
}
}
此時,ViewPager.setCurretItem方法也會失效,想經過點擊Tab button 切換page也沒法實現。
ViewPager.setOnTouchListener(new View.OnTouchListener(){
on touch ( xx ){
return true;
}
});
這種方式能夠實現只禁止滑動翻頁,能夠經過setCurrentItem,來切換頁面。