上一篇是ViewAnimation(补间动画),这一篇是帧动画,通过每次播放一帧drawable资源实现动画效果。像是传统的动画方式,把一系列图片按照某一顺序播放,形成连贯的效果。
使用帧动画比较简单:
- 现在drawable目录下自定义一个xml文件,用以指定要展示的图片和持续的事件还有是否循环播放。
- 在Java代码中使用
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/animationIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:src="@drawable/fairy" />
<Button
android:id="@+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:text="播放动画" />
<Button
android:id="@+id/buttonB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="停止播放" />
</LinearLayout>
图片资源文件
在drawable目录下新建 xml文件,并将图片资源放在drawable下
在文件中指定显示的图片和一些属性
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@drawable/dance01"
android:duration="150"></item>
<item
android:drawable="@drawable/dance02"
android:duration="150"></item>
</animation-list>
JavaCode
package com.example.drawable;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.drawable.AnimatedImageDrawable;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
// 声明控件
private ImageView animationIV;
private Button buttonA,buttonB;
private AnimationDrawable animationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到控件
animationIV = findViewById(R.id.animationIV);
buttonA = findViewById(R.id.buttonA);
buttonB = findViewById(R.id.buttonB);
// 设置点击事件监听器
buttonA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animationIV.setImageResource(R.drawable.fairy);
animationDrawable = (AnimationDrawable) animationIV.getDrawable();
animationDrawable.start();
}
});
buttonB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
animationDrawable = (AnimationDrawable) animationIV.getDrawable();
animationDrawable.stop();
}
});
}
}