属性动画
1、属性动画简介
Android开始提供了两种动画,逐帧动画和补间动画(frame-by-frame animation & tweened animation),补间动画是对View进行一系列动画操作,作用只能在View上,有很大缺陷。因此google推出了属性动画,属性动画不只是视觉上的动画效果,而实际上是一种不断地对值操作的机制。可以是任意对象的任意属性能
2、ValueAnimator
是属性动画中最核心的一个类,根据初始值和结束值,动画时长计算动画的平滑过渡
ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(300);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float currentValue = (float) animation.getAnimatedValue();
Log.d("Anim", "------>" + currentValue);
}
});
// 延迟播放时间
// anim.setStartDelay();
// 循环播放次数
// anim.setRepeatCount(1);
// 重新播放和倒序播放 ValueAnimator.RESTART ValueAnimator.REVERSE
// anim.setRepeatMode(ValueAnimator.RESTART);
anim.start();
3、ObjectAnimator
可以操作任意对象
float curTranslationX = text_view.getTranslationX();
ObjectAnimator animator = ObjectAnimator.ofFloat(text_view, "translationX", curTranslationX, -500f);
animator.setDuration(5000);
animator.start();
ObjectAnimator.ofFloat(text_view, "scaleY", 1f, 3f, 1f).setDuration(5000).start();
4、组合动画的实现
AnimatorSet实现了组合动画
after(Animator anim) 将现有动画插入到传入的动画之后执行
after(long delay) 将现有动画延迟指定毫秒后执行
before(Animator anim) 将现有动画插入到传入的动画之前执行
with(Animator anim) 将现有动画和传入的动画同时执行
ObjectAnimator moveIn = ObjectAnimator.ofFloat(text_view, "translationX", -500f, 0f);
ObjectAnimator rotate = ObjectAnimator.ofFloat(text_view, "rotation", 0f, 360f);
ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(text_view, "alpha", 1f, 0f, 1f);
AnimatorSet animSet = new AnimatorSet();
animSet.play(rotate).with(fadeInOut).after(moveIn);
animSet.setDuration(5000);
animSet.start();
5、Animator监听
动画的监听可以有两种实现,根据需求决定是否完整实现
// 动画监听的全部方法
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// 开始
}
@Override
public void onAnimationEnd(Animator animation) {
// 结束
}
@Override
public void onAnimationCancel(Animator animation) {
// 取消
}
@Override
public void onAnimationRepeat(Animator animation) {
// 重复执行
}
});
// 实现动画监听的部分方法
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
}
});
浙公网安备 33010602011771号