Differentiating between user scroll and programatic page change in ViewPager

后端 未结 3 1927
野的像风
野的像风 2021-01-30 05:25

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

3条回答
  •  终归单人心
    2021-01-30 06:04

    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.

提交回复
热议问题