android animate() withEndAction() vs setListener() onAnimationEnd()
Asked Answered
E

1

24

Often I use ViewPropertyAnimator and set end action using its withEndAction() function like:

view.animate().translationY(0).withEndAction(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}).start();

But also you can set end action setting special listener like:

view.animate().translationY(0).setListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        // do something
    }
});

So what is the difference between these two approaches and when I should use each of them?

Earthward answered 8/12, 2015 at 9:37 Comment(0)
D
23

There is no big difference, take a look at the souce code.

Both are executed on onAnimationEnd.

But the runnable gets removed after it was started. So The Runnable is just executed once and the Listener might be called multiple times.

@Override
public void onAnimationEnd(Animator animation) {
    mView.setHasTransientState(false);
    if (mListener != null) {
        mListener.onAnimationEnd(animation);  // this is your listener
    }
    if (mAnimatorOnEndMap != null) {
        Runnable r = mAnimatorOnEndMap.get(animation); // this is your runnable
        if (r != null) {
            r.run();
        }
            mAnimatorOnEndMap.remove(animation);
    }
    if (mAnimatorCleanupMap != null) {
        Runnable r = mAnimatorCleanupMap.get(animation);  
        if (r != null) {
            r.run();
        }
        mAnimatorCleanupMap.remove(animation);
    }
    mAnimatorMap.remove(animation);
}
Dispersant answered 8/12, 2015 at 9:58 Comment(1)
No problem. I hope you get some more upvotes. In my opition this was a pretty interesting question. :)Dispersant

© 2022 - 2024 — McMap. All rights reserved.