How to disable swiping in specific direction in ViewPager2

后端 未结 3 1841
遥遥无期
遥遥无期 2021-01-22 20:59

I want to disable right to left swipe in ViewPager2. I basically have a viewpager2 element with 2 pages in my navigation drawer. I want my second page to show up on

3条回答
  •  自闭症患者
    2021-01-22 21:13

    I found a listener which can listen when the user tries to swipe, it'll then check the current page, if it's the first page, disable the user input else enable it as it was by default.

    Here's the code snippet for that:-

            pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageScrollStateChanged(int state) {
                    super.onPageScrollStateChanged(state);
                    if (state == SCROLL_STATE_DRAGGING && pager.getCurrentItem() == 0) {
                        pager.setUserInputEnabled(false);
                    } else {
                        pager.setUserInputEnabled(true);
                    }
                }
            });
    

    Since my scenario was of 2 pages only, checking the page number would be good for me, but in case we have more than 2 pages and we need to disable the swipe in one particular direction, we may use onPageScrolled(int position, float positionOffset, int positionOffsetPixels) listener of viewpager2 and handle the desired scenario according to the positive or negative values of position and positionOffset.

提交回复
热议问题