一、實現方式
(1)代碼中添加實現
- 將圖片添加到AnimationDrawable對象,在將對象添加到imageView中,調用start()方法啟動動畫。
AnimationDrawable animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.drawable.a), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.b), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.c), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.d), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.e), 200);
animationDrawable.setOneShot(true);//設置是否只播放一次
imageView.setImageDrawable(animationDrawable);
animationDrawable.start();
(2)生成 animation-list 的資源文件,在代碼中引用。
- 在drawable文件下新建abunation_list的xml文件,在文件中添加圖片資源。
- 將xml文件添加到imageView中,通過getDrawable方法獲取AnimationDrawable對象,調用start()方法啟動動畫。
<?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/a"
android:duration="1000" />
<item
android:drawable="@drawable/b"
android:duration="1000" />
<item
android:drawable="@drawable/c"
android:duration="1000" />
<item
android:drawable="@drawable/d"
android:duration="1000" />
<item
android:drawable="@drawable/e"
android:duration="1000" />
</animation-list>
- oneshot:設置是否只播放一次,默認為false
- drawable:設置當前圖片資源
- duration:設置當前圖片時間
imageView.setBackgroundResource(R.drawable.anim_list);
animationDrawable = (AnimationDrawable) imageView.getDrawable();
animationDrawable.start();
注意方式:
- 在onResume方法中添加它,防止發生空指針異常。
- 不建議添加太大的圖片,因為這很容易導致OOM。