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">
<ImageView
android:id="@+id/actionImg"
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="@drawable/action_animation"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/startBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="开始动画"/>
<Button
android: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;
@Override
protected 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() {
@Override
public void onClick(View v) {
if (animationDrawable == null){
// 获取背景图片
animationDrawable = (AnimationDrawable) actionImg.getBackground();
// 启动动画
animationDrawable.start();
}
}
};
/**
* 结束动画
* */
View.OnClickListener endActionClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (animationDrawable != null){
// 停止动画
animationDrawable.stop();
animationDrawable = null;
}
}
};
所需图片和文件目录: