Differentiating between user scroll and programatic page change in ViewPager

OK, so it turns out that I was right about the answer lying in ViewPager.onPageChangeListener. In particular it lies in using onPageScrollStateChanged(int state). Essentially there are three states that a page in a ViewPager can be in:

  1. Dragging: Indicates that the pager is currently being dragged by the user.
  2. Idle: Indicates that the pager is in an idle, settled state.
  3. Settling: Indicates that the pager is in the process of settling to a final position.

So the dragging state only occurs when the current page is being physically dragged by the user. Thus when the user has swiped a page the states occur in the following order: Dragging -> Settling -> Idle. Now, the onPageSelected(int position) method is called between the “Settling” and “Idle” states. Thus, in order to determine whether or not a page change was caused by a user scroll one just needs to check that the previous state was “dragging” and that the current state is “Settling”. You can then keep a boolean variable to track whether or not the page change was user initiated or not and check it in your onPageSelected(int position) method.

Here is my onPageScrollStateChanged method

public void onPageScrollStateChanged(int state) 
{
    if (previousState == ViewPager.SCROLL_STATE_DRAGGING
            && state == ViewPager.SCROLL_STATE_SETTLING)
        userScrollChange = true;

    else if (previousState == ViewPager.SCROLL_STATE_SETTLING
            && state == ViewPager.SCROLL_STATE_IDLE)
        userScrollChange = false;

    previousState = state;
}

The if and else if statements need not be so explicit but I did so for clarity.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)