我的应用程序中有android.support.v4.view.ViewPager
,我已实现TimerTask
自动滚动页面并使用自定义Scroller来缩短页面转换动画时间。我试图在用户手动滚动页面时停止自动滚动。
我从下面的SO问题中听了@Vikram的回答,但程序化滚动被检测为用户滚动。并且在单个滚动中多次调用 viewPager.OnPageChangeListener 。
Differentiating between user scroll and programatic page change in ViewPager
有没有办法在此设置中降低转换速度或区分用户滚动和程序化滚动?
这是我的自定义Scroller类
public class FixedSpeedScroller extends Scroller {
private int mDuration = 1000;
public FixedSpeedScroller(Context context) {
super(context);
}
public FixedSpeedScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public FixedSpeedScroller(Context context, Interpolator interpolator, boolean flywheel) {
super(context, interpolator, flywheel);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}}
这是我的viewPager设置
public void setUpViewPager() {
mIndicator = (PageIndicatorView) findViewById(R.id.pivGroupFlyer);
mPager = (ViewPager) findViewById(R.id.vpGroupFlyer);
mPager.setAdapter(new GroupFlyerAdapter(this, mFlyerList));
Field mScroller = null;
try {
mScroller = ViewPager.class.getDeclaredField("mScroller");
mScroller.setAccessible(true);
FixedSpeedScroller scroller = new FixedSpeedScroller(mPager.getContext(), new DecelerateInterpolator());
mScroller.set(mPager, scroller);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
mIndicator.setVisibility(View.VISIBLE);
mIndicator.setAnimationType(AnimationType.WORM);
mIndicator.setRadius(2);
mIndicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == mFlyerList.size()) {
currentPage = 0;
progChange = true;
}
progChange = true;
mPager.setCurrentItem(currentPage++, true);
}
};
final Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(Update);
}
}, 4000, 5000);
if (!(mFlyerList.size() == 0)) {
mGroupHeader.setVisibility(View.INVISIBLE);
}
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(positionOffsetPixels == 0 ){
} else {
if(progChange) {
//programmatically-initiated
Log.e("APP", "SCROLL");
} else {
//user-initiated touch scroll
Log.e("USER", "SCROLL");
swipeTimer.cancel();
}
progChange = false;
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}