我正在使用ObjectAnimator为viewPager设置动画。 viewpager嵌套在RecyclerView中。如果在objectAnimator动画期间滚动,则会抛出IndexOutOfBound异常。这是代码段:
ObjectAnimator objectAnimator = ObjectAnimator
.ofFloat(new PagerHintMovement(-10, viewPager), "progress", -1f, 1f);
objectAnimator.setInterpolator(new AccelerateInterpolator());
objectAnimator.setDuration(1500);
objectAnimator.setRepeatCount(1);
objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
Log.i(TAG, "Animation: Starting fake drag on view pager.");
viewPager.beginFakeDrag();
}
@Override
public void onAnimationEnd(Animator animation) {
Log.i(TAG, "Animation: Ending fake drag on view pager.");
viewPager.endFakeDrag();
viewPager.setCurrentItem(viewPager.getCurrentItem());
}
@Override
public void onAnimationCancel(Animator animation) {
viewPager.setCurrentItem(viewPager.getCurrentItem());
}
@Override
public void onAnimationRepeat(Animator animation) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) {
if (animation.getInterpolator() instanceof AccelerateInterpolator) {
animation.setInterpolator(new DecelerateInterpolator());
} else {
animation.setInterpolator(new AccelerateInterpolator());
}
}
}
});
objectAnimator.setStartDelay(1000);
objectAnimator.start();
这是PagerMovement类。调用setProgress时会引发异常。 viewPager.fakeDragBy(目标*进度)导致IndexOutOfBound异常。
class PagerHintMovement {
float goal;
float progress;
ViewPager viewPager;
PagerHintMovement(float goal, ViewPager viewPager) {
this.goal = goal;
this.viewPager = viewPager;
}
public float getProgress() {
return progress;
}
public void setProgress(float progress) {
this.progress = progress;
if (viewPager.isFakeDragging()) {
Log.i("GalleryViewPagerAdapter",
"Animation: Updating fake drag with value=" + goal * progress + "px");
viewPager.fakeDragBy(goal * progress);
}
}
}