1、
Frame动画是一系列图片按照一定的顺序展示的过程,也就是说它是一张张图片快速显示的过程,让人看起来像是动画一样,我们称为逐帧动画。Frame动画可以被定义在XML文件中,也可以完全编码实现。
如果要实现的动画资源是被定义在XML里面,我们可以将它放到/res的anim目录下(可以自己新建一下目录),或者直接放到/drawable底下,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:oneshot="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/anim_1"
android:duration="120"></item>
<item
android:drawable="@drawable/anim_2"
android:duration="120"></item>
<item
android:drawable="@drawable/anim_3"
android:duration="120"></item>
<item
android:drawable="@drawable/anim_4"
android:duration="120"></item>
</animation-list>
注意:上面要改成animation-list标签,其中android:oneshot="false"
表示的意思是一直循环播放,默认值为true,也就是只播放一个循环,这里我们设置为一直播放。
然后我放置了四个item,也就是四张图片,按自己想要播放的顺序排列一下就好,其中的android:duration="120"
属性表示图片显示的时间,这里是毫秒为单位,表示120毫秒。
2、
接下来我们新建一个空的activity,然后去改布局文件。
那我们是要让图片一帧一帧地显示,所以无疑我们要加入一个ImageView标签,这边我们一定要把之前我们设计好的定义动画的XML给引用过来,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/fram_image"
android:layout_width="200dp"
android:layout_height="260dp"
android:background="@drawable/fram_anim"/>
</LinearLayout>
这边我是把图片作为背景来实现的,当然也可以用src.
3、
最后,我们要在activity中去实现相应的逻辑了。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fram_animation);
ImageView imageView = (ImageView) findViewById(R.id.fram_image);
imageView.setImageResource(R.drawable.fram_anim);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
animationDrawable.start();
}
我们要先实例化对象,也就是我们之前在布局文件中命名的fram_anim,然后用这个对象来绑定获取我们设置好的动画资源:imageView.setImageResource(R.drawable.fram_anim);
继而获取设置好的动画背景:
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
当一切都准备就绪了,就可以开始动画了。