装载补间动画文件需要使用 android.view.animation.AnimatioUtils.loadAnimation(Context context,int id);
id 表示 动画xml 文件的资源ID.假设在res\anim 目录下有一个动画文件test.xml ,装载test.xml 文件的代码如下:
Animation animation = AnimationUtils.loadAnimation(this, R.anim.test);
假设有一个LinearLayout 组件(layout), 将test.xml 文件中设置的补间动画应用到layout 的方式有2 种
1. 使用layout 类的startAnimation 方法, 如下:
layout.startAnimation(animation);
2. 使用 Animation 类的start 方法,代码如下:
layout.setAnimation(animation);
animation.start();
如果需要循环显示动画, 可如下设置:
animation.setRepeatCount(Animation.INFINITE);
以下讲解示例
1. 移动补间动画: 循环向右移动的EditText 与上下弹跳的球
2. 缩放补间动画, 通过<scale> 标签可以定义缩放补间动画
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator"
android:fromXScale="0.2" android:toXScale="1.0" android:fromYScale="0.2"
android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%"
android:duration="2000" />
这个xml 中属性的含义如下
android:fromXScale 表示沿X 轴缩放的起始比例 android:toXScale 表示沿X轴缩放的结束比例
android:fromYScale 表示沿Y 轴缩放的起始比例 android:toYScale 表示沿Y轴缩放的结束比例
(以上4个属性的取值规则为 0.0 表示收缩到没有,1.0 表示不收缩 ,大于1.0 表示将组件放大到相应的比例,如1.5表示放大到原组件的1.5倍, 小于1.0表示将组件缩小到相应的比例,如0.5 表示缩小到原组件的50% )
android:pivotX 表示沿X轴方向缩放的支点位置。 如果该属性值为50%, 则支点在沿X轴的中心位置
android:pivotY 表示沿Y轴方向缩放的支点位置。 如果该属性值为50%, 则支点在沿Y轴的中心位置
一个示例: 跳动的心
3. 旋转补间动画, 通过<rotate>标签可以定义旋转补间动画
<rotate xmlns:android="http://schema.android.com/apk/res/android"
android:interpolator="@anim/linear_interpolator" android:fromDegress="0"
android:toDegress="360" android:pivotX="50%" android:pivotY="50%"
android:duration="10000" android:repeatMode="restart" android:repeatCount="infinite" />
<rotate> 标签有两个特有的属性
android:fromDegress: 表示旋转的起始角度 android:toDegress: 表示旋转的结束角度
还使用如下两个属性设置旋转的次数和模式:
android:repeatCount: 设置旋转的重复次数, 如果想让旋转永不停止,可以设置为infinite 或 -1, 该属性默认值为0
android:repeatMode: 设置重复的模式, 默认值是restart. 该属性只有android:repeatCount 设置为大于0或infinite 时才起作用。
除了可以设置为restart, 还可以设置为reverse, 表示偶数次显示动画时会做与动画文件定义的方向相反的动作.
4. 透明间补间动画 ,通过<alpha> 标签可以定义透明度补间动画, 由于比较简单,这里不列出
特别注意: 透明度0.0 表示完全透明(即完全看不到), 1.0 表示完全不透明(即完全清晰),须牢记
以下一个示例 投掷炸弹