Android (Android Studio)(Java) 实现ViewPager不能左右滑动

Android 实现ViewPager不能左右滑动


自己写一个类继承ViewPager,然后在布局里使用自己写的这个类

package 你自己的包名;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

//不能左右滑动的页面
//用法,在布局页面里把
//androidx.viewpager.widget.ViewPager
//改为
//你自己的包名.NOScrollViewPager
//因为NOScrollViewPager继承了ViewPager
public class NOScrollViewPager extends ViewPager {

    private boolean NoScroll = true;

    public void setNoScroll(boolean noScroll) {
        NoScroll = noScroll;
    }

    public NOScrollViewPager(@NonNull Context context) {
        super(context);
    }

    public NOScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void scrollTo(int x, int y) {
        super.scrollTo(x, y);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (NoScroll){
            return false;
        }else {
            return super.onTouchEvent(ev);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (NoScroll){
            return false;
        }else{
            return super.onInterceptTouchEvent(ev);
        }
    }

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

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

参考自B站小好https://www.bilibili.com/video/BV1Z7411i77y?p=11

你可能感兴趣的:(Android,Studio)