Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a repeat count/mode in a ViewPropertyAnimator?

Tags:

android

Is there a way to specify a repeat count / mode when using a ViewPropertyAnimator ?

like image 954
Softlion Avatar asked Oct 05 '22 10:10

Softlion


1 Answers

Unfortunetely the ViewPropertyAnimator does not have any method to specify the repeat count of the animation it performs. As stated in the javadocs for startAnimation() method in ViewPropertyAnimator:

Starts the underlying Animator for a set of properties. We use a single animator that simply runs from 0 to 1, and then use that fractional value to set each property value accordingly.

Unfortunetely the value animator it uses is private and we have no possibility to manipulate it's state in any other way than provided by the public methods of ViewPropertyAnimator.

Repeating Animation

specify anAnimatorListener for your ViewPropertyAnimator which will restart the animation after each iteration:

viewPropertyAnimator.setListener(new Animator.AnimatorListener() {

    ...

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

    ...

});
viewPropertyAnimator.start();

If you want to specify the exact number of execution, introduce a variable this way:

int[] repeatCount = {8}; //your repeat count goes here

viewPropertyAnimator.setListener(new Animator.AnimatorListener() {

    ...

    @Override
    public void onAnimationEnd(Animator animation) {
        if(repeatCount-- > 0)
            viewPropertyAnimator.start();
    }

    ...

});
viewPropertyAnimator.start();

EDIT

You should be noted, though, the values which gets animated by ViewPropertyAnimator (start and end values) are stored within the instance of ViewPropertyAnimator and are therefore not refreshed after each animation. So if you would like to animate incrementaly some properties of the view after each iteration, make sure to create a new instance of the animator before each start. Like so:

public void animateEndlessly(final View v) {
        ViewPropertyAnimator viewPropertyAnimator = v.animate().scaleX(1.5f).scaleY(1.5f).setDuration(300);
        viewPropertyAnimator.setListener(new Animator.AnimatorListener() {

            ...

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

            ...

        });
        viewPropertyAnimator.start();
    }
like image 84
Andrzej Chmielewski Avatar answered Nov 04 '22 19:11

Andrzej Chmielewski