1.简介
帧动画非常容易理解,其实就是简单的由N张静态图片收集起来,然后我们通过控制依次显示这些图片,因为人眼"视觉残留"的原因,会让我们造成动画的"错觉",跟放电影的原理一样。
而Android中实现帧动画,一般我们会用到AnimationDrawable 先编写好Drawable,然后代码中调用start()以及stop()开始或停止播放动画。
2.代码实现
补:AndroidStudio中帧动画相关的xml文件放在drawable文件夹中而不是anim文件夹中。
2.1.图片资源
2.2.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="@drawable/progress_loading_image_01" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_02" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_03" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_04" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_05" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_06" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_07" android:duration="100" />
<item android:drawable="@drawable/progress_loading_image_08" android:duration="100" />
</animation-list>
android:oneshot="false":设置动画是否只播放一次,true:只播放一次,false:循环播放。
android:duration="100":相隔两张图片播放时间间隔。单位/毫秒。
2.3.Activity代码
/**
* 帧动画
*/
public class FrameAnimationActivity extends AppCompatActivity {
private Button startbtn;
private Button stopbtn;
private ImageView imageView;
private AnimationDrawable animationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frameanimation);
imageView = findViewById(R.id.img_show);
animationDrawable = (AnimationDrawable) imageView.getBackground();
//开始
startbtn = findViewById(R.id.btn_start);
startbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
animationDrawable.start();
}
});
//结束
stopbtn = findViewById(R.id.btn_stop);
stopbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
animationDrawable.stop();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != animationDrawable && animationDrawable.isRunning()) {
animationDrawable.stop();
}
}
}
2.4.Activity布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止" />
<ImageView
android:id="@+id/img_show"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:background="@drawable/start_show" />
</LinearLayout>
2.4.效果
完成代码:https://github.com/wujianning/AndroidAnimation
附1:补间动画讲解:Android 动画之补间动画
附2:属性动画详解:Android 动画之属性动画