为了能让动画直接与对应控件相关联,以使我们从监听动画过程中解放出来,谷歌的开发人员在 ValueAnimator 的基础上,又派生了一个类 ObjectAnimator;该类可以使用ValueAnimator类中的所有方法。又重新写了几个方法,比如 ofInt(),ofFloat()等,其中比较关键的方法是ofFloat()。
我们先看看利用 ObjectAnimator 重写的 ofFloat 方法如何实现一个动画:(改变透明度)
(1)setAlpha 渐变动画
ObjectAnimator animator = ObjectAnimator.ofFloat(bt_animate,"alpha",1,0,1);
animator.setDuration(4000);
animator.setInterpolator(new LinearInterpolator());
animator.start();
可以看到构造方法非常加单:
public static ObjectAnimator ofFloat(Object target, String propertyName, float... values)
(2).旋转动画:
private void rotation() {
ObjectAnimator animator = ObjectAnimator.ofFloat(bt_animate,"rotation",0,270,180);
animator.setDuration(4000);
animator.setInterpolator(new LinearInterpolator());
animator.start();
}
private void rotationY() {
ObjectAnimator animator = ObjectAnimator.ofFloat(bt_animate,"rotationY",0,270,180);
animator.setDuration(4000);
animator.setInterpolator(new LinearInterpolator());
animator.start();
}
(3)setTranslationX,setTranslationY相应的移动动画:
ObjectAnimator animator = ObjectAnimator.ofFloat(tv, "translationX", 0, 200, -200,0);
animator.setDuration(2000);
animator.start();
ObjectAnimator animator = ObjectAnimator.ofFloat(tv, "translationY", 0, 200, -100,0);
animator.setDuration(2000);
animator.start();
(4)、setScaleX 与 setScaleY
ObjectAnimator animator = ObjectAnimator.ofFloat(tv, "scaleX", 0, 3, 1);
animator.setDuration(2000);
animator.start();
(5)也可以自定义接口:set+驼峰式,如代码中的只要该类中有写setTransformationValue既可。
private void initAnimations(int transformDuration) {
transformation = ObjectAnimator.ofFloat(this, "transformationValue", 0);
transformation.setInterpolator(new DecelerateInterpolator(3));
transformation.setDuration(transformDuration);
transformation.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationEnd(Animator animation) {
transformationRunning = false;
setIconState(animatingIconState);
}
});
}
public void setTransformationValue(float value) {
this.transformationValue = value;
invalidateSelf();
}