示例1:直接在代码中实现
public class MainActivity extends Activity { private Button btn1, btn2; private ImageView iv; private int[] ids = { R.drawable.anim_0010001, R.drawable.anim_0010002, R.drawable.anim_0010003, R.drawable.anim_0010004, R.drawable.anim_0010005, R.drawable.anim_0010006, R.drawable.anim_0010007, R.drawable.anim_0010008, R.drawable.anim_0010009, R.drawable.anim_0010010, R.drawable.anim_0010011, R.drawable.anim_0010012, R.drawable.anim_0010013, R.drawable.anim_0010014, R.drawable.anim_0010015, }; private AnimationDrawable animationDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.p_w_picpathView1); btn1 = (Button) findViewById(R.id.button1); btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { animationDrawable = new AnimationDrawable(); for (int i = 0; i < ids.length; i++) { animationDrawable.addFrame( getResources().getDrawable(ids[i]), 100); } iv.setBackgroundDrawable(animationDrawable); animationDrawable.setVisible(true, true); animationDrawable.start(); } }); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { animationDrawable.stop(); } }); } }
示例2:利用xml文件实现
在Drawbale文件夹下建一个animation-list 类型的xml文件。取名为anim_list:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/anim_0010001" android:duration="100"> </item> <item android:drawable="@drawable/anim_0010002" android:duration="100"> </item> <item android:drawable="@drawable/anim_0010003" android:duration="100"> </item> <!-- 每个Item加载一张图片资源,再次不再罗列过多 --> </animation-list>
布局文件:(注意ImageView的背景设置)
<ImageView android:id="@+id/p_w_picpathView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/anim_list"/>
MainActivity.java:
public class MainActivity extends Activity { private Button btn1, btn2; private ImageView iv; private AnimationDrawable animationDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.p_w_picpathView1); btn1 = (Button) findViewById(R.id.button1); btn2 = (Button) findViewById(R.id.button2); animationDrawable =(AnimationDrawable) iv.getBackground(); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { animationDrawable.start(); } }); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { animationDrawable.stop(); } }); } }