I have a android.support.v4.view.ViewPager
in my application and I would like to differentiate between a programmatically-initiated smooth scroll and a user-initiat
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:
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.