带有 setStartOffset 的 AnimationSet 不起作用

AnimationSet with setStartOffset not working

我正在尝试使用 AnimationSet

在视图上 运行 几个动画(一个接一个)

1 --> 0 扩展到 0 --> 1

AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new AccelerateDecelerateInterpolator());

ScaleAnimation animation1 = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animation1.setDuration(500);

ScaleAnimation animation2 = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animation2.setDuration(500);
animation2.setStartOffset(500);

animationSet.addAnimation(animation1);
animationSet.addAnimation(animation2);

mFloatingActionButton.startAnimation(animationSet);

视图刚刚消失,一秒钟后再次出现。没有动画。

如果我删除 setStartOffset(...) 我可以看到动画,但看不到我想要的动画。

我在这里错过了什么?

使用开始偏移的链接动画很少会按预期运行。 有几种方法可以达到你想要的效果:

1) 使用 ScaleAnimations,您可以使用侦听器链接动画(在 onAnimationEnd 回调中启动第二个动画)。

2) 使用 animatorSets(相对于 animationSets)和 playSequentially。

选项 1 的简化代码:

final View theView = findViewById(R.id.the_view);
final ScaleAnimation scaleAnimation1 = new ScaleAnimation(1,0,1,0);
final ScaleAnimation scaleAnimation2 = new ScaleAnimation(0,1,0,1);
scaleAnimation1.setAnimationListener(new Animation.AnimationListener()
{
    @Override
    public void onAnimationStart(Animation animation)
    {
    }
     @Override
    public void onAnimationEnd(Animation animation)
    {
        theView.startAnimation(scaleAnimation2);
    }
     @Override
    public void onAnimationRepeat(Animation animation)
    {
    }
});

选项 2 的简化代码:

final View theView = findViewById(R.id.the_view);

ObjectAnimator animScaleXSmaller = ObjectAnimator.ofFloat(theView, "scaleX", 0f);
ObjectAnimator animScaleYSmaller = ObjectAnimator.ofFloat(theView, "scaleY", 0f);
AnimatorSet animScaleXYSmaller = new AnimatorSet();
animScaleXYSmaller.setDuration(500);
animScaleXYSmaller.playTogether(animScaleXSmaller, animScaleYSmaller);

ObjectAnimator animScaleXBigger = ObjectAnimator.ofFloat(theView, "scaleX", 1f);
ObjectAnimator animScaleYBigger = ObjectAnimator.ofFloat(theView, "scaleY", 1f);
AnimatorSet animScaleXYBigger = new AnimatorSet();
animScaleXYBigger.setDuration(500);
animScaleXYBigger.playTogether(animScaleXBigger, animScaleYBigger);

AnimatorSet animScaleBounce = new AnimatorSet();
animScaleBounce.playSequentially(animScaleXYSmaller, animScaleXYBigger);
animScaleBounce.setInterpolator(new AccelerateDecelerateInterpolator());
animScaleBounce.start();