禁止viewpager左右滑动

package com.example.xinenhuadaka.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

//禁止左右滑动的viewpager
public class NoScrollViewPager extends ViewPager {

    private boolean noScroll = true;

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

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

    //调用此方法 参数为false 即可禁止滑动
    public void setNoScroll(boolean noScroll) {
        this.noScroll = noScroll;
    }

    @Override
    public void scrollTo(int x, int y) {
//        if(noScroll){  //加上判断无法用 setCurrentItem 方法切换
            super.scrollTo(x, y);
//        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        if (!noScroll)
            return false;
        else
            return super.onTouchEvent(arg0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        if (!noScroll)
            return false;
        else
            return super.onInterceptTouchEvent(arg0);
    }

    @Override
    public void setCurrentItem(int item, boolean smoothScroll) {
        super.setCurrentItem(item, smoothScroll);
    }

    @Override
    public void setCurrentItem(int item) {
        super.setCurrentItem(item);
    }


}

调用

mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        };
        viewpager.setAdapter(mAdapter);
        viewpager.setOffscreenPageLimit(fragmentList.size());//保存全部fragment
        viewpager.setNoScroll(false);//禁止滑动
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                vp.setCurrentItem(position,false);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

当scrollTo方法中加入if判断时

viewpager.setNoScroll(true);//允许滑动
//设置当前点击的Tab所对应的页面
viewpager.setCurrentItem(position, false);//切换页面
viewpager.setNoScroll(false);//禁止滑动

亲测有效

你可能感兴趣的:(android,viewpager)