天天看點

禁止ViewPager左右滑動

最近在做一個二手校園交易平台的畢設,想達到仿鹹魚的tab效果。目前效果:

禁止ViewPager左右滑動

但是鹹魚的是不可以左右滑動的,怎麼禁止ViewPager左右滑動呢?

建一個ViewPager的子類,重寫它的 onInterceptTouchEvent 和 onTouchEvent方法:

package com.up.uwei.shshop.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class NoSwipeViewPager extends ViewPager {
    private boolean canSwipe = true;
    public NoSwipeViewPager(Context context, AttributeSet attributeSet){
        super(context, attributeSet);
    }
    public void setCanSwipe(boolean canSwipe)
    {
        this.canSwipe = canSwipe;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return canSwipe && super.onTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return canSwipe && super.onInterceptTouchEvent(ev);
    }
}
           

接着在布局裡使用NoSwipeViewPager:

禁止ViewPager左右滑動

然後在Activity裡通過findById拿到我們的NoSwipeViewPAger,接着調用:

禁止ViewPager左右滑動
禁止ViewPager左右滑動

然後運作結果:

禁止ViewPager左右滑動

ok,已經不能左右滑動,隻能通過替補tab來控制,

但是有一個問題,每次切換fragment都有一個動畫,比如從 “導航” 到 “我的”,中間有動畫,不想要怎麼辦?

答:

mViewPager.setCurrentItem(3, false);
           
禁止ViewPager左右滑動

最後運作結果:

禁止ViewPager左右滑動

嘿嘿,over....

繼續閱讀