Android的Viewpager反弹到半页Android、Viewpager、到半页

2023-09-06 04:49:08 作者:花谢忽如雪

那么,我想实现的是用户会打开视图寻呼机的第一页,视图寻呼机会反弹到一半的第二页,并反弹至拳头页面表明有更多的页面滚动到。我想知道我如何能实现呢?

So what i am trying to achieve is user would open to first page of the view pager, and the view pager would bounce to half of the second page and bounce back to the fist page indicating that there are more pages to scroll to. I was wondering on how i could implement this?

推荐答案

您可以使用fakeDragBy的方法来达到这种效果:

You can use fakeDragBy method to achieve this effect:

viewPager.beginFakeDrag();
viewPager.fakeDragBy(offset); //offset in pixels. 
viewPager.endFakeDrag();

编辑:

我已经做方法如下:

private int animFactor;
private ValueAnimator animator = new ValueAnimator();

private void animateViewPager(final ViewPager pager, final int offset, final int delay) {
    if (!animator.isRunning()) {
        animator.removeAllUpdateListeners();
        animator.removeAllListeners();
        //Set animation
        animator.setIntValues(0, -offset);
        animator.setDuration(delay);
        animator.setRepeatCount(1);
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = animFactor * (Integer) animation.getAnimatedValue();
                if (!pager.isFakeDragging()) {
                    pager.beginFakeDrag();
                }
                pager.fakeDragBy(value);
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                animFactor = 1;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                pager.endFakeDrag();
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                animFactor = -1;
            }
        });
        animator.start();
    }
}

使用示例:

animateViewPager(pager, 10, 1000);

EDIT2: ValueAnimator是类API级别11.还设置寻呼机适配器调用此方法之前

ValueAnimator is class for Api level 11. Also set pager adapter before calling this method.