Android之Dedug--Circular dependencies cannot exist in AnimatorSet

时间:2021-12-22 20:10:06

今日,在学习AnimatorSet时,使用play、with、after、before时,代码书写如下:

ObjectAnimator animator1 = ObjectAnimator.ofFloat(v,"translationX",300f);
ObjectAnimator animator2 = ObjectAnimator.ofFloat(v,"scaleX",1f,0f,1f);
ObjectAnimator animator3 = ObjectAnimator.ofFloat(v,"scaleY",1f,0f,1f);
AnimatorSet set = new AnimatorSet();
set.setDuration(1000);
set.play(animator1).after(animator2).before(animator3).with(animator2);
set.start();

运行代码时,报错,错误报告如下:

12-12 16:26:18.210 28528-28528/com.zhangmiao.animationdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zhangmiao.animationdemo, PID: 28528
java.lang.IllegalStateException: Circular dependencies cannot exist in AnimatorSet
at android.animation.AnimatorSet.sortNodes(AnimatorSet.java:921)
at android.animation.AnimatorSet.start(AnimatorSet.java:539)
at com.zhangmiao.animationdemo.ObjectAnimatorDemo.onClick(ObjectAnimatorDemo.java:82)
at android.view.View.performClick(View.java:4868)
at android.view.View$PerformClick.run(View.java:20294)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:5718)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:975)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

然后,我将set.play(animator1).after(animator2).before(animator3).with(animator2);代码修改为set.play(animator1);这时并不会报错,我依次添加动画,当添加到set.play(animator1).after(animator2).before(animator3).with(animator2);时,才会报错,所以是最后一个with(animator2)有问题,然后,我又添加了一个动画

ObjectAnimator animator4 = ObjectAnimator.ofFloat(v,"scaleY",1f,0f,1f);

将set.play(animator1).after(animator2).before(animator3).with(animator2);修改为

set.play(animator1).after(animator2).before(animator3).with(animator4);

代码就不会报错了。

所以,得到的结论是:

AnimatorSet的play、with、before、after函数不可复用同一个Animator,如果需要使用同样的Animator,可以创建多个相同动画的Animator,然后分别使用这多个动画即可。