How to play multiple Animations using AnimatorSet?

笑着哭i 提交于 2021-01-27 12:22:31

问题


I'm using Sceneform to create an android app that plays animation. I'm trying to start multiple Animators sequentially using AnimatorSet. The code works perfectly when trying to play two animations, but whenever I add a 3rd animation, the first two animations play then the app crashes.

Here's a piece of the code:

    List<Animator> animatorList = new ArrayList<Animator>();

    AnimationData ad1 = JimRenderable.getAnimationData("Abm_09|A");

    Animator a = new ModelAnimator(ad1, JimRenderable);
    animatorList.add(a);

    AnimationData ad2 = JimRenderable.getAnimationData("Abm_09|B");

    a = new ModelAnimator(ad2, JimRenderable);
    animatorList.add(a);

    AnimationData ad3 = JimRenderable.getAnimationData("Abm_09|C");

    a = new ModelAnimator(ad3, JimRenderable);
    animatorList.add(a);

    AnimatorSet as= new AnimatorSet();
    as.playSequentially(animatorList);
    as.start();

How can I let it play more than just 2 animations?


回答1:


AnimatorSet public class, which extends Animator class, provides a mechanism to group animations together so that they run in relation to one another. You can set animations to play simultaneously, sequentially, or after a specified delay.

Here's how your code should look like:

AnimatorSet bouncer = new AnimatorSet();

bouncer.play(bounceAnim).before(squashAnim1);

// THESE FOUR ANIMATIONS PLAY SIMULTANEOUSLY
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
bouncer.play(squashAnim1).with(stretchAnim2);

bouncer.play(bounceBackAnim).after(stretchAnim2);

ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(bouncer).before(fadeAnim);

animatorSet.start();

In this code squashAnim1 clip plays simultaneously with squashAnim2, stretchAnim1, and stretchAnim2.

And this example explains how it works: we set up an AnimatorSet to play:

  • anim1 and anim2 at the same time,
  • anim3 to play when anim2 finishes,
  • and anim4 to play when anim3 finishes:

    AnimatorSet clips = new AnimatorSet();
    clips.play(anim1).with(anim2);
    clips.play(anim2).before(anim3);
    clips.play(anim4).after(anim3);
    

Also, you might use Animation listeners. They can listen for important events during an animation's duration. Here's a code how it looks like:

ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);

fadeAnim.addListener(new AnimatorListenerAdapter() {
    public void onAnimationEnd(Animator animation) {
        balls.remove(((ObjectAnimator)animation).getTarget());
    }
}

Hope this helps.



来源:https://stackoverflow.com/questions/55681374/how-to-play-multiple-animations-using-animatorset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!