按顺序播放AnimatorSet中的暂停

时间:2015-09-08 14:19:19

标签: android animation objectanimator

我需要将以下动画应用于imageView:

1. alpha (0 -> 1) and scale (0 -> 1) in 500ms
2. pause for 1000ms
3. alpha (1 -> 0) and scale (1 -> 0) in 500ms

在我看来,这三个Animator可以按AnimatorSet顺序播放。

我编写了这段代码,其中三个块已经清楚地分开了:

ObjectAnimator alpha1 = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0f, 1f);
ObjectAnimator scaleX1 = ObjectAnimator.ofFloat(imageView, View.SCALE_X, 0f, 1f);
ObjectAnimator scaleY1 = ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 0f, 1f);
AnimatorSet part1 = new AnimatorSet();
part1.setInterpolator(new OvershootInterpolator());
part1.setDuration(500);
part1.playTogether(alpha1, scaleX1, scaleY1);

ObjectAnimator pause = ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f);
pause.setDuration(1000);

ObjectAnimator alpha0 = ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f, 0f);
ObjectAnimator scaleX0 = ObjectAnimator.ofFloat(imageView, View.SCALE_X, 1f, 0f);
ObjectAnimator scaleY0 = ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 1f, 0f);
AnimatorSet part2 = new AnimatorSet();
part2.setInterpolator(new AccelerateDecelerateInterpolator());
part2.setDuration(500);
part2.playTogether(alpha0, scaleX0, scaleY0);

在我看来,这段代码很清楚,比定时器或听众更好。 主要问题是,是否有一种“PauseAnimator可用于类似情况? (实际上第二个代码块什么都不做,它在1000毫秒内将alpha从1动画到1)

1 个答案:

答案 0 :(得分:2)

setStartDelay()方法可用于此目的。此外,PropertyValuesHolder可用于同时为视图的不同属性设置动画。

以下是高级别的步骤:

  1. 将objectAnimator1设置为动画提升alpha并平行升级x和y
  2. 将objectAnimator2设置为并行降低动画并降低缩放x和y并启动延迟
  3. 使用AnimatorSet为序列中的objectAnimator1和objectAnimator2设置动画。
  4. 以下是代码:我的视图是一个名为" mTextView"

    的文本视图
    // objectAnimator1 stuff
    PropertyValuesHolder pvhToRaiseAlpha = PropertyValuesHolder.ofFloat("alpha", 0f, 1.0f);
    PropertyValuesHolder pvhForxUpscale = PropertyValuesHolder.ofFloat("scaleX", 0f, 1.0f);
    PropertyValuesHolder pvhForyUpscale = PropertyValuesHolder.ofFloat("scaleY", 0f, 1.0f);
    ObjectAnimator objectAnimator1 = ObjectAnimator.ofPropertyValuesHolder(mTextView, pvhToRaiseAlpha, pvhForxUpscale, pvhForyUpscale);
    objectAnimator1.setDuration(500);
    
    // objectAnimator2 stuff
    PropertyValuesHolder pvhToLowerAlpha = PropertyValuesHolder.ofFloat("alpha", 1.0f, 0f);
    PropertyValuesHolder pvhForxDownscale = PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0f);
    PropertyValuesHolder pvhForyDownscale = PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0f);
    ObjectAnimator objectAnimator2 = ObjectAnimator.ofPropertyValuesHolder(mTextView, pvhToLowerAlpha, pvhForxDownscale, pvhForyDownscale);
    objectAnimator2.setDuration(500);
    objectAnimator2.setStartDelay(1000);
    
    // AnimatorSet stuff
    AnimatorSet sequenceAnimator = new AnimatorSet();
    sequenceAnimator.playSequentially(objectAnimator1, objectAnimator2);
    sequenceAnimator.start();