上一篇的动画介绍谈了动画的一些基本使用方法,这一篇谈谈动画的进一步使用。
ObjectAnimator
- 对属性使用该动画时,要提供setter/getter方法
- ObjectAnimator.ofXXX()创建动画对象
- 调用start()方法开始动画
- 可以为动画设置时间等
public class TestView extends View {
......
public void setProgress(float progress) {
this.progress = progress;
invalidate();
}
public float getProgress() {
return progress;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF rectF=new RectF(10,10,10+progress,10+getHeight());
canvas.drawRect(rectF,mPaint);
}
public void startAnim(){
ObjectAnimator animator=ObjectAnimator.ofInt(this,"progress",0,120);
animator.setDuration(2000);
animator.start();
}
......
}
为ObjectAnimator同时设置多个动画属性:
PropertyValuesHolder holder1=PropertyValuesHolder.ofFloat("scaleX",1);
PropertyValuesHolder holder2=PropertyValuesHolder.ofFloat("translateX",100);
PropertyValuesHolder holder3=PropertyValuesHolder.ofFloat("alpha",1);
ObjectAnimator animator1=ObjectAnimator.ofPropertyValuesHolder(view,holder1,holder2,holder3);
animator1.start();
ViewPropertyAnimator
ViewPropertyAnimator对象可以通过View.aniamte()获取。
可以看看它的源码:
public ViewPropertyAnimator animate() {
if (mAnimator == null) {
mAnimator = new ViewPropertyAnimator(this);
}
return mAnimator;
}
ViewPropertyAnimator可以使用链式设置属性:
view.animate()
.alpha(1.0f)
.scaleY(0.5f)
.translationX(0.5f)
.setDuration(2000).start();
AnimatorSet
这是动画集合,在上篇有提到,这此时使用它来控制多个动画属性的顺序:
AnimatorSet animatorSet=new AnimatorSet();
//动画一次执行 animatorSet.playSequentially(animator1,animator2);
animatorSet.start();
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.play(animator1).before(animator2);//Animator1先执行
animatorSet.playTogether(animator1,animator3);//animator1跟animator3同时执行
animatorSet.start();
Keyframe
场景:一个进度条先滑动到100%,然后再滑回到实际的进度。这是使用Keyframe是罪合适并且比较简单。
//开始的时候进度为0
Keyframe k1=Keyframe.ofFloat(0,0);
//50%的时候进度为300
Keyframe k2=Keyframe.ofFloat(0.5f,300);
//100%的时候进度为100
Keyframe k3=Keyframe.ofFloat(1,100);
PropertyValuesHolder holder=PropertyValuesHolder.ofKeyframe("progress",k1,k2,k3);
ObjectAnimator animator1=ObjectAnimator.ofPropertyValuesHolder(this,holder);
animator1.setDuration(3000);
animator1.start();
插值器
作用:根据时间的流逝的百分比来计算出当前属性值改变的百分比
- LinearInterpolator:线性插值器,匀速动画
- AccelerateDecelerateInterpolator:加速减速插值器,动画两头慢,中间块
- DecelerateInterpolator:减速插值器,动画越来越慢
- OvershootInterpolator:回弹,
动画会超过目标值一些,然后再弹回来。效果看起来有点像你一屁股坐在沙发上后又被弹起来一点的感觉
…….(文档)
动画监听器
AnimatorListener的定义:
public static interface AnimatorListener {
void onAnimationStart(Animator animation);
void onAnimationEnd(Animator animation);
void onAnimationCancel(Animator animation);
void onAnimationRepeat(Animator animation);
}
根据它的名字大概可以知道是在什么时候回调:
- onAnimationStart:动画开始后
- onAnimationEnd:动画结束后
- onAnimationCancel:动画取消后
- onAnimationRepeat:动画重复
注意:调用cancel后,会执行onAnimationEnd方法,在onAnimationCancel方法后执行。
AnimatorUpdateListener的定义:
public static interface AnimatorUpdateListener {
void onAnimationUpdate(ValueAnimator animation);
}
监听整个动画的过程,动画的每播放一帧都会回调该方法。
O文明K,本次动画使用介绍到此结束,希望大家可以指出哪些不对。