类似于电影一样,一帧一帧的播放图片
同样,创建AnimationDrawable有两种方式
- XML文件+Java代码
- Java代码方式
不同于之前的ViewAnimation,之前的动画xml文件存放位置是:res/anim/xxx.xml
而AnimationDrawable存放位置是:res/drawable/xxx.xml
XML文件+Java代码
anim_drawable.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/record_04"
android:duration="300"/>
<item
android:drawable="@mipmap/record_05"
android:duration="300"/>
<item
android:drawable="@mipmap/record_07"
android:duration="300"/>
<item
android:drawable="@mipmap/record_09"
android:duration="300"/>
<item
android:drawable="@mipmap/record_11"
android:duration="300"/>
</animation-list>
- android:oneshot:是否只循环播放一次。默认是false,一直循环播放;true,表示只播放一次
- item标签,每一个标签代表一个Drawable资源:
- android:drawable:drawable资源引用
- android:duration:没一帧持续播放的时长
Java代码
mIvImg.setBackgroundResource(R.drawable.animation_drawable);
AnimationDrawable animationDrawable = (AnimationDrawable) mIvImg.getBackground();
animationDrawable.start();
animationDrawable.stop();
Java代码方式
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void startAnimationDrawable() {
//创建帧动画
AnimationDrawable animationDrawable = new AnimationDrawable();
//添加帧
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.record_04), 300);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.record_05), 300);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.record_07), 300);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.record_09), 300);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.record_11), 300);
//设置动画是否只播放一次, 默认是false
animationDrawable.setOneShot(false);
//根据索引获取到那一帧的时长
int duration = animationDrawable.getDuration(2);
//根据索引获取到那一帧的图片
Drawable drawable = animationDrawable.getFrame(0);
//判断是否是在播放动画
boolean isRunning = animationDrawable.isRunning();
//获取这个动画是否只播放一次
boolean isOneShot = animationDrawable.isOneShot();
//获取到这个动画一共播放多少帧
int framesCount = animationDrawable.getNumberOfFrames();
//把这个动画设置为background,兼容更多版本写下面那句
mIvImg.setBackground(animationDrawable);
mIvImg.setBackgroundDrawable(animationDrawable);
//开始播放动画
animationDrawable.start();
//停止播放动画
animationDrawable.stop();
}
注意:我这里的动画时直接写在点击事件里面,如果你想让一看到界面就开始动画,不能叫start( )的方法写在onCreate里面
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
animationDrawable.start();
}