SwipeRefreshLayout intercepts with ViewPager

inspired by @Crosswind and @Gombal: kotlin extension function solution for ViewPager2

binding.topViewPager.ignorePullToRefresh(binding.swipeRefreshLayout)

fun ViewPager2.ignorePullToRefresh(swipeRefreshLayout: SwipeRefreshLayout) {
    this.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageScrollStateChanged(state: Int) {
            super.onPageScrollStateChanged(state)
            if (!swipeRefreshLayout.isRefreshing) {
                swipeRefreshLayout.isEnabled = state == SCROLL_STATE_IDLE
            }
        }
    })
}

Checking the page scroll state is a good approach but when a user changed the page then the animating spinner will disappear and it's bad UX.

To fix this:

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout) {
    @Override
    public void onPageScrollStateChanged(int state) {
        if (swipeRefreshLayout != null && !swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setEnabled(state == ViewPager.SCROLL_STATE_IDLE);
        }
    }
});

public class CSwipeRefreshLayout extends SwipeRefreshLayout {
  private int mTouchSlop;
  private float mPrevx;
  private float mPrevy;
  public CSwipeRefreshLayout(Context context) {
    this(context, null);
  }

  public CSwipeRefreshLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
  }

  @Override
  public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
      case MotionEvent.ACTION_DOWN:
        mPrevx = MotionEvent.obtain(ev).getX();
        mPrevy = MotionEvent.obtain(ev).getY();
        break;
      case MotionEvent.ACTION_MOVE:
        final float evX = ev.getX();
        final float evy = ev.getY();
        float xDiff = Math.abs(evX - mPrevx);
        float yDiff = Math.abs(evy - mPrevy);
        if (xDiff > mTouchSlop && xDiff > yDiff) {
          return false;
        }
    }
    return super.onInterceptTouchEvent(ev);
  }
}

I managed to solve it:

mainViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mainTabLayout) {
    @Override
    public void onPageScrollStateChanged(int state) {
        toggleRefreshing(state == ViewPager.SCROLL_STATE_IDLE);
    }
});

your toggleRefreshing() should then look something like this:

public void toggleRefreshing(boolean enabled) {
    if (swipeRefreshLayout != null) {
        swipeRefreshLayout.setEnabled(enabled);
    }
}