回顾下ValueAnimator
对象常见的使用方式。
概述
ObjectAnimator
实际上继承了ValueAnimator
,能够直接操作对象属性来改变动画的执行效果,而ValueAnimator
主要是提供在执行动画过程中数值的计算,在开发中需要将计算的数值手动设置给动画执行的对象,以此来实现动画效果,因此ValueAnimator
使用起来更加灵活。
ofFloat方法
还是上篇文章中的按钮移动案例,布局不再贴出使用ValueAnimator
实现:
final Button btn = findViewById(R.id.bt_animation);
float x = btn.getTranslationX();
ValueAnimator animator = ValueAnimator.ofFloat(x, 400);
animator.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
btn.setTranslationX((Float) animation.getAnimatedValue());
}
});
animator.start();
实现效果:
ofInt方法
基本同ofFloat
方法。
ofArgb方法
在API 21
增加的该方法,执行一个红变蓝色的动画:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ValueAnimator animator = ValueAnimator
.ofArgb(
Color.parseColor("#ff0000"),
Color.parseColor("#0000ff"))
.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
btn.setBackgroundColor((Integer) animation.getAnimatedValue());
}
});
animator.start();
}
实现效果:
ofObject方法
同样实现平移动画,使用ofObject
方法:
final Button btn = findViewById(R.id.bt_animation);
float x = btn.getTranslationX();
ValueAnimator animator = ValueAnimator.ofObject(new FloatEvaluator(), x, 400);
animator.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
btn.setTranslationX((Float) animation.getAnimatedValue());
}
});
animator.start();
该方法需要传入TypeEvaluator
参数,并且TypeEvaluator
的evaluate()
方法的返回值需要和Values
的类型保持一致,否则会抛出类型转换异常,系统内置了几种常见的估值器:
ofPropertyValuesHolder方法
该方法可以执行一个动画集,比如同时执行translationX
和translationY
的平移动画:
final Button btn = findViewById(R.id.bt_animation);
float x = btn.getTranslationX();
float y = btn.getTranslationY();
PropertyValuesHolder holder1 = PropertyValuesHolder.ofFloat("translationX", x, 400);
PropertyValuesHolder holder2 = PropertyValuesHolder.ofFloat("translationY",y,400);
ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(holder1, holder2);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Float currentX = (Float) animation.getAnimatedValue("translationX");
Float currentY = (Float) animation.getAnimatedValue("translationY");
btn.setTranslationX(currentX);
btn.setTranslationY(currentY);
}
});
animator.setDuration(2000);
animator.start();
执行效果:
需要注意的是在onAnimationUpdate(ValueAnimator animation)
的监听中如果直接使用animation.getAnimatedValue()
不指定属性名的方法,获取到的值为第一个PropertyValuesHolder
中计算出的值。
关于该方法中的PropertyValuesHolder
对象 和涉及的ofKeyframe
方法在上篇文章中已经说明其使用方式:
属性动画使用解析(一):ViewPropertyAnimator和ObjectAnimator
setInterpolator方法
ValueAnimator
内置的默认插值器AccelerateDecelerateInterpolator
, 也就是先加速后减速。
可以通过setInterpolator()
方法设置需要的插值器,系统内置了几种常见的插值器:
setEvaluator方法
可以直接设置需要的估值器,内置估值器见上文。
其他
ValueAnimator
的其他方法不再列出。关于估值器和插值器另行总结其使用方法。