1、在res/drawable中创建***.xml文件
示例代码:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"android:oneshot="false"><!--控制<item> 标签执行一遍还是n遍--><item android:drawable="@drawable/action_one"android:duration="500"/><item android:drawable="@drawable/action_two"android:duration="500"/><item android:drawable="@drawable/action_three"android:duration="500"/><item android:drawable="@drawable/action_four"android:duration="500"/><item android:drawable="@drawable/action_five"android:duration="500"/><item android:drawable="@drawable/action_six"android:duration="500"/>
</animation-list>
2、布局文件
示例代码:
<?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"><ImageViewandroid:id="@+id/actionImg"android:layout_width="match_parent"android:layout_height="500dp"android:background="@drawable/action_animation"/><LinearLayoutandroid:orientation="horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/startBtn"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="开始动画"/><Buttonandroid:id="@+id/endBtn"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="结束动画"/></LinearLayout></LinearLayout>
3、java代码
代码示例:
private ImageView actionImg;private Button startBtn;private Button endBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 初始化图片控件actionImg = findViewById(R.id.actionImg);// 初始化开始按钮startBtn = findViewById(R.id.startBtn);startBtn.setOnClickListener(startActionClick);// 初始化结束按钮endBtn = findViewById(R.id.endBtn);endBtn.setOnClickListener(endActionClick);}private AnimationDrawable animationDrawable = null;// 图片对象/*** 开始动画* */View.OnClickListener startActionClick = new View.OnClickListener() {@Overridepublic void onClick(View v) {if (animationDrawable == null){// 获取背景图片animationDrawable = (AnimationDrawable) actionImg.getBackground();// 启动动画animationDrawable.start();}}};/*** 结束动画* */View.OnClickListener endActionClick = new View.OnClickListener() {@Overridepublic void onClick(View v) {if (animationDrawable != null){// 停止动画animationDrawable.stop();animationDrawable = null;}}};
所需图片和文件目录: