一.效果
1.activity的xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".anim.FrameActivity">
<Button
android:id="@+id/br_start"
android:text="启动"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/br_stop"
android:text="停止"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>
<ImageView
android:background="@drawable/frameanim"
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"></ImageView>
</LinearLayout>
其中ImageView的背景不是一张图片,而是一个animation-list集合,里面设置多张图片
2.drawable下的frameanim.xml文件
3.activity的java代码
- 获得图片的动画背景
AnimationDrawable animationDrawable = (AnimationDrawable) iv.getBackground(); - 启动
animationDrawable.start(); - 停止
animationDrawable.stop();
package com.example.android3_demo.anim;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import com.example.android3_demo.R;
import androidx.appcompat.app.AppCompatActivity;
public class FrameActivity extends AppCompatActivity implements View.OnClickListener {
private Button br_start;
private Button br_stop;
private ImageView iv;
private AnimationDrawable animationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame);
initView();
animationDrawable = (AnimationDrawable) iv.getBackground();
}
private void initView() {
br_start = (Button) findViewById(R.id.br_start);
br_stop = (Button) findViewById(R.id.br_stop);
iv = (ImageView) findViewById(R.id.iv);
br_start.setOnClickListener(this);
br_stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.br_start:
if(!animationDrawable.isRunning()){//如果不在运行
animationDrawable.start();//启动动画
}
break;
case R.id.br_stop:
if(animationDrawable.isRunning()){//如果在运行
animationDrawable.stop();//停止动画
}
break;
}
}
}