11

I have the ViewPager2 callback setup but need to detect when a user initiated page change has completed. The callback won't differentiate between user initiated and code initiated. Here's what I have now:

ViewPager2.OnPageChangeCallback swipeListener = new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { //I want to run code only if user initiated this page change //but this runs whether user initiated or code initiated } } 

The page change that is done via code:

viewPager.setCurrentItem(targetSlide); 

The docs for ViewPager2 show a isUserInputEnabled() method which tells you if a user "can" change the page manually, but I need to detect if the user "did" initiate the page change.

2 Answers 2

3

You can use isFakeDragging inside registerOnPageChangeCallback to detect whether the drag is fake or initiated by user.

Returns true if a fake drag is in progress.

...onPageScrolledonPageScrolled(int position, float positionOffset, int positionOffsetPixels){ if(isFakeDragging) {// fake scroll} else{// user scroll} } 
Sign up to request clarification or add additional context in comments.

5 Comments

I don't initiate a fake drag in code to change the page, so isFakeDragging will always return false here.
then what do you mean by code initiated? you need to add the complete details about your use case. Anyhow, if possible, use fake drag for best practices and desired behavior.
OP edited. I am using viewPager.setCurrentItem().
@lilbiscuit then the easy solution is to use a boolean flag to track the change or the other option is to use a touch event listener to detect the user touch and proceed accordingly.
How do you use the position to get the view that the viewPager2 is looking at?
0

One can override viewpager2 to detect a page change like so:

 viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.