我的AnimationSet中有2个动画。它们需要顺序发生,并且持续时间不同。如何使我的AnimationSet无限重复?

public void cartoonBreathing(ImageView v, int inhale_time, int exhale_time){
    AnimationSet breathing_set = new AnimationSet(true);

    Animation inhale = new ScaleAnimation(1.0f,2f,1.0f,2f,
            Animation.RELATIVE_TO_SELF,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f);
    inhale.setFillAfter(true);
    inhale.setDuration(inhale_time * 1000);

    Animation exhale = new ScaleAnimation(1.0f,0.5f,1.0f,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f);
    exhale.setFillAfter(true);
    exhale.setDuration(exhale_time * 1000);

    breathing_set.addAnimation(inhale);
    breathing_set.addAnimation(exhale);

    //breathing_set.setRepeatMode(Animation.RESTART); DOES NOT WORK
    //breathing_set.setRepeatMode(2); DOES NOT WORK
    //breathing_set.setRepeatCount(Animation.INFINITE);

    v.startAnimation(breathing_set);

}

最佳答案

AnimationSet上的documentation引用:


  AnimationSet继承Animation行为的方式很重要。应用于AnimationSet的某些Animation属性会影响AnimationSet本身,其中某些属性会下推到子级,而有些则会被忽略,如下所示:
  
  
  duration,repeatMode,fillBefore,fillAfter:将这些属性设置在AnimationSet对象上时,将向下推到所有子动画。
  repeatCount,fillEnabled:AnimationSet将忽略这些属性。
  startOffset,shareInterpolator:这些属性适用于AnimationSet本身。
  


这说明了您的尝试失败的原因。相反,可以在动画完成后使用Animation.AnimationListener重新启动动画:

public void cartoonBreathing(final ImageView v, int inhale_time, int exhale_time){
    final AnimationSet breathing_set = new AnimationSet(true);

    Animation inhale = new ScaleAnimation(1.0f,2f,1.0f,2f,
            Animation.RELATIVE_TO_SELF,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f);
    inhale.setFillAfter(true);
    inhale.setDuration(inhale_time * 1000);

    Animation exhale = new ScaleAnimation(1.0f,0.5f,1.0f,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f,
            Animation.RELATIVE_TO_SELF,0.5f);
    exhale.setFillAfter(true);
    exhale.setDuration(exhale_time * 1000);

    breathing_set.addAnimation(inhale);
    breathing_set.addAnimation(exhale);

    breathing_set.setAnimationListener(new Animation.Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation){}

        @Override
        public void onAnimationEnd(Animation animation)
        {
            v.startAnimation(breathing_set);
        }

        @Override
        public void onAnimationRepeat(Animation animation){}
    });

    v.startAnimation(breathing_set);
}


请注意,必须将ImageViewAnimationSet声明为final才能从AnimationListener内部进行访问

如果应用程序已停止,则可以考虑在clearAnimation()上调用ImageView

09-19 09:22