帧动画
特点
- 通过播放一组定义好的图片,像电影哪种方式,来实现的一种动画。
- 三种动画中实现最简单的,由于是纯加载图片实现动画,所以会消耗更多内存,也更容易产生OOM,所以使用图片越小越好。
- 通常用在一些简单的Loading图标,下拉上拉图标等。
- 作用于View(Button,TextView...),但不能修改View的属性(背景,颜色,大小...)
实现方式
- 通过XML文件来定义
res/anim的文件夹里创建动画效果.xml文件
xml代码
<?xml version="1.0" encoding="utf-8"?>
<animation-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true"> // 设置是否只播放一次,默认为false
// item = 动画图片资源;duration = 设置一帧持续时间(ms)
<item android:drawable="@drawable/a0" android:duration="100"/>
<item android:drawable="@drawable/a1" android:duration="100"/>
<item android:drawable="@drawable/a2" android:duration="100"/>
<item android:drawable="@drawable/a3" android:duration="100"/>
<item android:drawable="@drawable/a4" android:duration="100"/>
<item android:drawable="@drawable/a5" android:duration="100"/>
</animation-list>
复制代码
启动/停止
ImageView frameAnimationImage = (ImageView)findViewById(R.id.animation_frame_image);
frameAnimationImage.setImageResource(R.drawable.frame_animation_drawable);
AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.start();
AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.stop();
复制代码
- 通过Java代码来实现
//Java代码实现帧动画
AnimationDrawable animation = new AnimationDrawable();
//第一个参数为动画图片资源,第二个参数为执行时间
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_a), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_b), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_c), 200);
animation.setOneShot(false);
frameAnimationImage.setImageDrawable(animation);
animation.stop();
//特别注意:在动画start()之前要先stop(),不然在第一次动画之后会停在最后一帧,这样动画就只会触发一次
animation.start();
复制代码