一、逐帧动画实现
1. Frame动画是一系列图片按照一定的顺序展示的过程,和放电影的机制很相似,我们称为逐帧动画。Frame动画可以被定义在XML文件中,也可以完全编码实现(Frame-by-frame Animations).
2.在res/drawable目录下一个文件lottery_animlist.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@mipmap/lottery_1"
android:duration="200" />
<item
android:drawable="@mipmap/lottery_2"
android:duration="200" />
<item
android:drawable="@mipmap/lottery_3"
android:duration="200" />
<item
android:drawable="@mipmap/lottery_4"
android:duration="200" />
<item
android:drawable="@mipmap/lottery_5"
android:duration="200" />
<item
android:drawable="@mipmap/lottery_6"
android:duration="200" />
</animation-list>
根节点是animation-list(动画列表),里面有一个或者多个item节点组成,oneshot属性表示是否只播放一次,true
表示只会播放一次,false表示一直循环播放,内部用item节点声明一个动画帧,android:drawable指定此帧动画所
对应的图片资源,android:druation代表此帧持续的时间,整数,单位为毫秒。
3.用ImageView控件作为动画载体来显示动画
<ImageView
android:id="@+id/animation_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:src="@drawable/lottery_animlist" />
4.如果在代码里面实现,不在布局里面加载。那么,代码要写:
imageView.setImageResource(R.drawable.lottery_animlist);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
animationDrawable.start();
停止
imageView.setImageResource(R.drawable.lottery_animlist);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
animationDrawable.stop();
二、单纯用代码实现逐帧动画的话:
AnimationDrawable anim = new AnimationDrawable();
for (int i = 1; i <= 6; i++) {
int id = getResources().getIdentifier("lottery_" + i, "mipmap", getPackageName());
Drawable drawable = getResources().getDrawable(id);
anim.addFrame(drawable, 200);
}
anim.setOneShot(false);
imageView.setImageDrawable(anim);
anim.start();