问题:如何使用Android动画工具或AnimatorSet来实现一组动画效果?
解决方法:
使用XML定义动画效果: 创建一个XML文件,定义所需的动画效果,例如res/anim/fade_in.xml:
在代码中使用AnimationUtils加载并应用动画效果:
Animation fadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fade_in);
view.startAnimation(fadeInAnimation);
使用AnimatorSet组合多个属性动画:
ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(view, "scaleX", 0.5f, 1.0f);
scaleXAnimator.setDuration(1000);
ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(view, "scaleY", 0.5f, 1.0f);
scaleYAnimator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
animatorSet.start();
使用AnimatorSet按顺序播放多个属性动画:
ObjectAnimator fadeOutAnimator = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.0f);
fadeOutAnimator.setDuration(1000);
ObjectAnimator fadeInAnimator = ObjectAnimator.ofFloat(view, "alpha", 0.0f, 1.0f);
fadeInAnimator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(fadeOutAnimator, fadeInAnimator);
animatorSet.start();
使用AnimatorSet同时播放和按顺序播放多个属性动画:
ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(view, "scaleX", 0.5f, 1.0f);
scaleXAnimator.setDuration(1000);
ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(view, "scaleY", 0.5f, 1.0f);
scaleYAnimator.setDuration(1000);
ObjectAnimator fadeOutAnimator = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.0f);
fadeOutAnimator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
animatorSet.playSequentially(scaleXAnimator, scaleYAnimator, fadeOutAnimator);
animatorSet.start();
注意:要使用属性动画(ObjectAnimator),目标视图的属性需要有相应的setter方法。