onPageScrollStateChanged

onPageScrollStateChanged

本文介绍了在ViewPager中区分用户滚动和程序化页面更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我的应用程序中有一个android.support.v4.view.ViewPager,我想在程序启动的平滑滚动和用户启动的触摸滚动之间进行区分.

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-initiated touch scroll.

我看过ViewPager.OnPageChangeListener,我相信答案可能就在那里,但是我不确定如何.

I've had a look at ViewPager.OnPageChangeListener and I believe that the answer may lie in there but I'm just not sure how.

推荐答案

好,所以事实证明我对ViewPager.onPageChangeListener中的答案是正确的.特别地,它在于使用onPageScrollStateChanged(int state).本质上,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. 拖动:表示用户当前正在拖动寻呼机.
  2. 空闲:指示寻呼机处于空闲,已建立状态.
  3. 结算:表明传呼机正在结算到最终位置.

因此,仅当用户实际拖动当前页面时,才会发生拖动状态.因此,当用户滑动页面时,状态将按以下顺序发生:拖动->稳定->空闲.现在,在稳定"和空闲"状态之间调用onPageSelected(int position)方法.因此,为了确定页面变化是否是由用户滚动引起的,只需要检查先前的状态是拖动"并且当前状态是稳定".然后,您可以保留boolean变量以跟踪页面更改是否由用户启动,并在您的onPageSelected(int 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.

这是我的onPageScrollStateChanged方法

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;
}

ifelse if语句不必如此明确,但为清楚起见,我这样做了.

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

这篇关于在ViewPager中区分用户滚动和程序化页面更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:54