Android run animation in loop with view.animate()

Viewed 101

I want to start an animation of a button. The animation works fine, but I want the animation will repeat. How can I do this? I have look for an answer for days. My code:

floatingActionButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Start the animation
        v.animate().setDuration(200)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                    }
                })
                // Rotate
                .rotation(rotated ? 0f : 135f)
                // Move up in first click, and down in second
                .translationY(rotated ? 0f : -200f);
        rotated = !rotated;
    }
});

Can I repeat this animation "forever"?

1 Answers

ViewPropertyAnimator is mainly used for good basic stuff. Try to use more advanced ObjectAnimator class which gives you basically what you need: method setRepeatCount and additionally setRepeatMode.

If you still want to use view.animate() you can write some hacks like that:

floatingActionButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        repeatAnimation(v);
    }
});
private void repeatAnimation(View v) {
    // Start the animation
    v.animate().setDuration(200)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    rotated = !rotated;
                    repeatAnimation(v);
                }
            })
            // Rotate
            .rotation(rotated ? 0f : 135f)
            // Move up in first click, and down in second
            .translationY(rotated ? 0f : -200f);
}
Related