Im having trouble figuring out how to capture a swipe event on the last page of a view pager.
Basically the requirement is that when the user is on the last page, and they try to swipe to get to the next page, the activity should close.
I've tried doing this onPageScrolled but I cant seem to differentiate a left or right swipe when in there. When on the last page, the user should still maintain the functionality to move to the previous page.
So basically the case is
When on last page
if swipe prev (do normal behaviour)
if swipe next (finish activity)
Can anyone provide any suggestions? Thanks
You can easily do that by creating a custom class inherits from viewPager and override two methods: “onTouchEvent()” and “onInterceptTouchEvent()” and return true or false to disable and enable the swiping on certain touch events i.e say swiping.
Implement Swipe Views You can create swipe views using AndroidX's ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .
ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.
There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.
Here is working solution!!
Required variables
....
private boolean isLastPageSwiped;
private int counterPageScroll;
....
Inside onPageScrolled of ViewPager
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Here 6 is last position
if (position == 6 && positionOffset == 0 && !isLastPageSwiped){
if(counterPageScroll != 0){
isLastPageSwiped=true;
//Next Activity here
}
counterPageScroll++;
}else{
counterPageScroll=0;
}
}
You should include an fake blank page to your ViewPager
, when user swipes your actual last page, it comes to this fake one. When this fake one is visible finish the Activity
.
You should try this way, if it does not work, I can give you an example code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With