Android中的动画2(逐帧动画)

来源:互联网 发布:美国传播学专业知乎 编辑:程序博客网 时间:2024/06/05 16:35

逐帧动画就比较简单了,就是一帧一帧的播放动画,每一帧都是有我们来定义的。

在res/drawable文件夹下新建一个Root element为animation-list的xml文件,命名为animation

res/drawable/animation.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/lu"        android:duration="200" />    <item        android:drawable="@drawable/panda"        android:duration="200" />    <item        android:drawable="@drawable/taiger"        android:duration="200" />    <!--        一个item代表一帧        android:drawable 表示这一帧所显示的图片        android:duration 表示这一帧的持续时间    --></animation-list>

然后在activity布局中声明一个ImageVIew,并且该ImageVIew用src引用animation.xml

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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="com.demo.ln.exam.MainActivity">    <ImageView        android:id="@+id/image"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:src="@drawable/animation" /></RelativeLayout>

在MainActivity中获取AnimationDrawable实例,用该实例启动动画:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    ImageView imageView;    AnimationDrawable animationDrawable;    @TargetApi(Build.VERSION_CODES.KITKAT)    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        imageView = (ImageView) findViewById(R.id.image);        //获取AnimationDrawable的实例        animationDrawable = (AnimationDrawable) imageView.getDrawable();        //启动动画        animationDrawable.start();        imageView.setOnClickListener(this);    }    @Override    public void onClick(View v) {        //暂停动画        animationDrawable.stop();    }}

lu.png

lu.png

panda.png

panda.png

taiger.png

这里写图片描述

到这里逐帧动画就完结了,比较简单。