1.随便准备3张图片,放入drawable目录,也可以放在drawable-xxhpdi目录下。
2.在drawable目录下创建frame.xml文件,如下
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/bluetooth_break" android:duration="500"/> <item android:drawable="@drawable/bluetooth_scaning" android:duration="500"/> <item android:drawable="@drawable/button_bg" android:duration="500"/> </animation-list>
3.activity_main.xml布局文件如下
<?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="com.idt.os.frameplay.MainActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/img_test"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click1" android:text="start"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click2" android:text="stop"/> </LinearLayout>
4.MainActivity.java文件如下
package com.idt.os.frameplay; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { AnimationDrawable ad; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = (ImageView)findViewById(R.id.img_test); imageView.setBackgroundResource(R.drawable.frame); //将动画布局图片设成ImageView背景 ad = (AnimationDrawable) imageView.getBackground(); //获取动画Drawable } public void click1(View view) { ad.start(); //启动动画播放 } public void click2(View view) { ad.stop(); //停止动画播放 } }