问题
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 extendsAnimator
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 withsquashAnim2
,stretchAnim1
, andstretchAnim2
.
And this example explains how it works: we set up an AnimatorSet
to play:
anim1
andanim2
at the same time,anim3
to play whenanim2
finishes,and
anim4
to play whenanim3
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