6

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.

lilbiscuit
  • 2,109
  • 6
  • 32
  • 53

2 Answers2

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}
}
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • 1
    I don't initiate a fake drag in code to change the page, so `isFakeDragging` will always return `false` here. – lilbiscuit Jun 25 '20 at 14:32
  • 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. – Pavneet_Singh Jun 25 '20 at 17:05
  • 1
    OP edited. I am using `viewPager.setCurrentItem()`. – lilbiscuit Jun 25 '20 at 21:09
  • @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. – Pavneet_Singh Jun 26 '20 at 12:24
0

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

    viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
        }
    });
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Miguel Tomás
  • 1,714
  • 1
  • 13
  • 23