Temporarily/Dynamically disable single page in Viewpager

二次信任 提交于 2019-12-01 21:08:04

You're definitely going to want to create your own custom ViewPager subclass. I created a simple custom ViewPager called CustomSwipePager that will handle blocking user interaction when needed.

public class CustomSwipeViewPager extends ViewPager {

    private boolean mLastPageEnabled = false;
    private int mLastPageIndex = 0;

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

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

    public void setLastPageEnabled(boolean enabled) {
        mLastPageEnabled = enabled;
    }

    public void setLastPageIndex(int index) {
        mLastPageIndex = index;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event){

        if(!mLastPageEnabled && getCurrentItem() >= (mLastPageIndex - 1)) {
            // Always return false to disable user swipes
            return false;
        }

        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (!mLastPageEnabled && getCurrentItem() >= (mLastPageIndex - 1)) {
            // Always return false to disable user swipes
            return false;
        }

        return true;
    }
}

There are two key methods you will want to take advantage of in the class setLastPageEnabled() and setLastPageIndex(). You can set the last page index to whatever you need, in your case if you have three items you would set it to 2. Then also use setLastPageEnabled(false) to disable swiping or to re-enabled use setLastPageEnabled(true).

You can include this custom view into your layout like this:

<com.mypackage.CustomSwipeViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_swipe_view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

And finally reference it in your Fragment or Activity in the appropriate place:

private CustomSwipeViewPager mPager;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    mPager = (CustomSwipeViewPager) findViewById(R.id.custom_swipe_view_pager);
    mPager.setLastPageEnabled(false);
    mPager.setLastPageIndex(2);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!