How can I repeat a property animation?

2019-02-22 08:39发布

I'm doing an animation of bubbles on the screen, but the bubbles stop after finishing the animation time. How do I repeat the animation or make it infinite?

bub.animate();
bub.animate().x(x2).y(y2);
bub.animate().setDuration(animationTime);       
bub.animate().setListener(new AnimatorListenerAdapter() {

    @Override
    public void onAnimationStart(Animator animation) {
        animators.add(animation); 
    } 

    @Override
    public void onAnimationRepeat(Animator animation) {
    }

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

4条回答
一纸荒年 Trace。
2楼-- · 2019-02-22 09:21
final ViewPropertyAnimator animator = view.animate().rotation(360).setInterpolator(new LinearInterpolator()).setDuration(1000); //Animator object

    animator.setListener(new android.animation.Animator.AnimatorListener() {
        ...

        @Override
        public void onAnimationEnd(final android.animation.Animator animation) {
            animation.setListener(this); //It listens for animation's ending and we are passing this to start onAniationEnd method when animation ends, So it works in loop
            view.setRotation(0);
            view.animate().rotation(360).setInterpolator(new LinearInterpolator()).setDuration(1000).setListener(this).start();
        }

    });
查看更多
爷、活的狠高调
3楼-- · 2019-02-22 09:22

You can use CycleInterpolator. For example, like this:

    int durationMs = 60000;
    int cycleDurationMs = 1000;
    view.setAlpha(0f);
    view.animate().alpha(1f)
            .setInterpolator(new CycleInterpolator(durationMs / cycleDurationMs))
            .setDuration(durationMs)
            .start();
查看更多
冷血范
4楼-- · 2019-02-22 09:25

This is actually possible. Here's an example of rotating a view:

        final ViewPropertyAnimator animator = view.animate().rotation(360).setInterpolator(new LinearInterpolator()).setDuration(1000);

        animator.setListener(new android.animation.Animator.AnimatorListener() {
            ...

            @Override
            public void onAnimationEnd(final android.animation.Animator animation) {
                animation.setListener(null);
                view.setRotation(0);
                view.animate().rotation(360).setInterpolator(new LinearInterpolator()).setDuration(1000).setListener(this).start();
            }

        });

You can also use "withEndAction" instead of a listener.

查看更多
再贱就再见
5楼-- · 2019-02-22 09:28

Since ViewPropertyAnimator is only good for simple animations, use more advanced ObjectAnimator class - basically method setRepeatCount and additionally setRepeatMode.

查看更多
登录 后发表回答