ApiDemos – BouncingBalls分析
这个例子主要是介绍属性动画的使用的,关于属性动画的一些关键设定的值,我们在上一篇文章大致描述了一番。另外,在分析这个例子之前,我们需要知道属性动画的类层次关系,这样便于理解和使用。
它的层次关系如下:
图1 Animator类继承图
BouncingBalls类是一个普通的Activity,它添加了一个自定义的MyAnimationView到主界面中。我们先看这个MyAnimationView的构造函数是怎样的:
public class MyAnimationView extends View {
public MyAnimationView(Contextcontext) {
super(context);
// Animate background color
// Note that setting the background color will automatically invalidatethe
// view,so that the animated color, and the bouncing balls, get redisplayed on
// every frame of the animation.
ValueAnimator colorAnim =ObjectAnimator.ofInt(this, "backgroundColor", RED, BLUE);
colorAnim.setDuration(3000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();
}
MyAnimationView继承自View类,是个自定义View,它在构造函数里启动了一个属性动画,即colorAnim.start()。
这里面用到了一个ObjectAnimator,这个对象动画控制器可以直接作用于某个对象。还记得我们上节讲到的属性动画的几个关键步骤是哪些吗?设置属性动画,必然离不开这几个关键步骤,否则动画是不可能成功的。在本例中这个ObjectAnimator也同样做了这几步:
1) 选定对象(Object)+属性(Property):简称 O + P;
ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor", RED, BLUE);
Object = this;
P = “backgroundColor”,这是View的背景色的属性值,也同时说明View中必然存在方法setP()以及getP(),即setBackgroundColor和getBackgroundColor;
2) 时长(Duration):简称D;
colorAnim.setDuration(3000);
D = 3000ms=3s
3) 时间插值(Time interpolation