在API Demo的View->Animation下可以找到四个Animation的Demo,第一个3D Translate比较复杂,最后再讲,先讲第2个Interpolator。该Activity对应的是view包内的Animation3.java,和layout的animation_3.xml。
界面的布局不加解释了,就一个Spinner和一个TextView。不是本文内容。
主要解释下几个重点语句。
初始化Animation,从类的名字可以看出是一个变换View的位置的动画,参数起点横坐标,终点横坐标,起点纵坐标,终点纵坐标。
- Animation a = new TranslateAnimation(0.0f,
- targetParent.getWidth() - target.getWidth() - targetParent.getPaddingLeft() -
- targetParent.getPaddingRight(), 0.0f, 0.0f);
下面是动画的参数设置,我加上了注释
- a.setDuration(1000);//设置动画所用的时间
- a.setStartOffset(300);//设置动画启动的延时
- //设置重复模式,RESTART为结束后重新开始,REVERSE为按原来的轨迹逆向返回
- a.setRepeatMode(Animation.RESTART);
- //设置重复次数,INFINITE为无限
- a.setRepeatCount(Animation.INFINITE);
- //根据用户在Spinner的选择设置target的进入的方式
- switch (position) {
- case 0:
- //加速进入
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.accelerate_interpolator));
- break;
- case 1:
- //减速进入
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.decelerate_interpolator));
- break;
- case 2:
- //加速进入.与第一个的区别为当repeatMode为reverse时,仍为加速返回原点
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.accelerate_decelerate_interpolator));
- break;
- case 3:
- //先往后退一点再加速前进
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.anticipate_interpolator));
- break;
- case 4:
- //减速前进,冲过终点前再后退
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.overshoot_interpolator));
- break;
- case 5:
- //case 3,4的结合体
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.anticipate_overshoot_interpolator));
- break;
- case 6:
- //停止前来回振几下
- a.setInterpolator(AnimationUtils.loadInterpolator(this,
- android.R.anim.bounce_interpolator));
- break;
- }
- //让target开始执行这个动画
- target.startAnimation(a);
- }
这里使用的是Android已预设的一些动作,我们也可以自定义XML来实现更好看的动画效果的,这个下一篇再讲。
除了TranslationAnimation,还有AlphaAnimation、RotateAnimation、ScaleAnimation,使用这几个基体动作的组合,可以形成一系列复杂的动画效果。具体用法请查看SDK。
整个都比较简单,就一个函数的调用,还不懂的看一下API的注释和SDK文档,没什么难理解的。