一.概念
幀動畫也叫Drawable Animation,是最簡單最直覺的動畫類型,他利用人眼的視覺暫留效應——也就是光對視網膜所産生的視覺在光停止作用後,仍會保留一段時間的現象。在Android中實作幀動畫,就是由設計師給出一系列狀态不斷變化的圖檔,開發者可以指定動畫中每一幀對應的圖檔和持續時間,然後就可以開始播放動畫了。具體有兩種方式可以實作幀動畫,分别是采用XML資源檔案和代碼實作。
二.實作
◆XML資源檔案方式
1.在res/drawable目錄中放入需要的圖檔

2.在res/drawable目錄中建立animlist.xml檔案,其中oneshot表示是否循環播放false為循環播放,duration表示圖檔停留的時間。
<?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/a1"
android:duration="120"/>
<item android:drawable="@drawable/a2"
android:duration="120"/>
<item android:drawable="@drawable/a3"
android:duration="120"/>
<item android:drawable="@drawable/a4"
android:duration="120"/>
<item android:drawable="@drawable/a5"
android:duration="120"/>
<item android:drawable="@drawable/a6"
android:duration="120"/>
<item android:drawable="@drawable/a7"
android:duration="120"/>
</animation-list>
3.在布局檔案中進行設定
<ImageView
android:id="@+id/image"
android:background="@drawable/animlist"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content" />
4.代碼中播放動畫
AnimationDrawable animationDrawable= (AnimationDrawable) imageView.getBackground();
//開始動畫
animationDrawable.start();
//結束動畫
animationDrawable.stop();
◆代碼動态實作
AnimationDrawable animationDrawable=new AnimationDrawable();
for(int x=1;x<8;x++){
int id=getResources().getIdentifier("a"+x,"drawable",getPackageName());
Drawable drawable=getResources().getDrawable(id);
animationDrawable.addFrame(drawable,120);
}
//設定是否循環播放
animationDrawable.setOneShot(false);
imageView.setBackgroundDrawable(animationDrawable);
//開始動畫
animationDrawable.start();
//結束動畫
animationDrawable.stop();
效果展示
image