ViewPager是一个很常见的组件,不仅支持收拾滑动切换页面,我们还可以通过viewPager.setCurrentItem(index)
来切换到指定的页面,那么他们如何区分呢?
我们知道ViewPager可以添加ViewPager.OnPageChangeListener
监听器,可以监听切换的状态。通过观察ViewPager.OnPageChangeListener#onPageScrollStateChanged(int state)
方法中state的输出,发现了手势切换和自动切换的规律,具体规律如下:
手势滑动翻页的log:
OnPageChangeListener onPageScrollStateChanged state:1
OnPageChangeListener onPageScrollStateChanged state:2
OnPageChangeListener onPageSelected position:1
OnPageChangeListener onPageScrollStateChanged state:0
代码翻页的log:
OnPageChangeListener onPageScrollStateChanged state:2
OnPageChangeListener onPageSelected position:9
OnPageChangeListener onPageScrollStateChanged state:0
根据log可以得出如下结论:
手势滑动翻页,是1、2、0(ViewPager.SCROLL_STATE_DRAGGING、ViewPager.SCROLL_STATE_SETTLING、ViewPager.SCROLL_STATE_IDLE)
代码翻页,是2、0(ViewPager.SCROLL_STATE_SETTLING、ViewPager.SCROLL_STATE_IDLE)
根据这个规律,我们可以写出以下代码:我们在onPageScrollStateChanged
判断是否是手动的状态,并且可以在onPageSelected
方法中使用这个状态。
/**
* 是否是用户手动切换ViewPager
*/
private boolean manualDraging = false;
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
LogUtils.e(TAG, "OnPageChangeListener onPageScrolled:" + position);
}
@Override
public void onPageSelected(int position) {
// 如果是手动模式,就暂停播放,同时清除掉各种状态;
if (manualDraging) {
LogUtils.e(TAG, "手动切换");
} else {
LogUtils.e(TAG, "代码切换");
}
}
@Override
/**
* 代码翻页,是2、0(ViewPager.SCROLL_STATE_SETTLING、ViewPager.SCROLL_STATE_IDLE)
* 手动滑动翻页,是1、2、0(ViewPager.SCROLL_STATE_DRAGGING、ViewPager.SCROLL_STATE_SETTLING、ViewPager.SCROLL_STATE_IDLE)
* {@link ViewPager.SCROLL_STATE_IDLE}
* {@link ViewPager.SCROLL_STATE_DRAGGING}
* {@link ViewPager.SCROLL_STATE_SETTLING}
*/
public void onPageScrollStateChanged(int state) {
LogUtils.e(TAG, "OnPageChangeListener onPageScrollStateChanged state:" + state);
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
manualDraging = false;
break;
case ViewPager.SCROLL_STATE_DRAGGING:
manualDraging = true;
break;
case ViewPager.SCROLL_STATE_SETTLING:
break;
default:
break;
}
}
});