一,animation_list.xml中靜態配置幀動畫的順序,如下:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true" >
<item android:drawable="@drawable/animation_1" android:duration="1000"/>
<item android:drawable="@drawable/animation_2" android:duration="100"/>
<item android:drawable="@drawable/animation_3" android:duration="100"/>
<item android:drawable="@drawable/animation_4" android:duration="100"/>
<item android:drawable="@drawable/animation_5" android:duration="100"/>
</animation-list>
1,android:duration="100" 指的是相應幀持續的時間。
2,android:oneshot 的配置 如果為true,表示動畫只播放一次停止在最后一幀上,如果設置為false表示動畫循環播放。
二、方法中調用,如下:
二、方法中調用,如下:
mImageView.setImageResource(R.drawable.animation_list); animationDrawable = (AnimationDrawable) mImageView.getDrawable(); animationDrawable.start();
當然,也可以在方法中動態設置動畫的播放,調用如下方法:
void setOneShot(boolean oneShot):設置AnimationDrawable是否執行一次,true執行一次,false循環播放
這時也可以中途控制動畫的播放與停止,如下所示:
mImageView.setImageResource(R.drawable.animation_list); animationDrawable = (AnimationDrawable) mImageView.getDrawable(); if(animationDrawable.isRunning()){ //當前AnimationDrawable是否正在播放
animationDrawable.stop(); //停止播放逐幀動畫。
} animationDrawable.start(); //開始播放逐幀動畫。
三、OOM解決方案(一):
使用以上方法基本可以解決20張圖片以內的幀動畫了,但是圖片一多,便會報OOM錯誤,
以下是我的一個解決方案,不是最好的,我也覺得有很多問題,但確實解決了這個問題,
姑且稱為方案一,相信我還會想到更好的解決方案,到時候再與大家分享
1,首先在初始化時,直接初始化兩個數組,一個保存每一幀照片,另一個保存每一幀圖片的持續時間
images = new int [42]; images[0] = R.drawable.animation_0; //動畫開始時的動畫
images[1] = R.drawable.animation_1; images[2] = R.drawable.animation_2; images[3] = R.drawable.animation_3; ...... images[40] = R.drawable.animation_40; images[41] = R.drawable.animation_41; //動畫結束時的畫面
durations = new int[40] ; durations[0] = 200; //事件觸發后多長時間開始動畫
durations[1] = 100; durations[2] = 200; ...... durations[40] = 300;
2,新建myAnimation類:
public class myAnimation{ private ImageView mImageView; //播方動畫的相應布局
private int[] mImageRes; private int[] durations; public myAnimation(ImageView pImageView, int[] pImageRes, int[] durations) { this.mImageView = pImageView; this.durations = durations; this.mImageRes= pImageRes; mImageView.setImageResource(mImageRes[1]); play(1); } private void play(final int pImageNo) { mImageView.postDelayed(new Runnable() { //采用延遲啟動子線程的方式
public void run() { mImageView.setImageResource(mImageRes[pImageNo]); if (pImageNo == mImageRes.length-1) return; else play(pImageNo + 1); } }, durations[pImageNo-1]); } }
3,在監聽事件中新建一個myAnimation類的對象即可:
new myAnimation(ImageView, images,durations);
--------------------------------------------------------------------------------------------
剛開始學習,寫博客只是希望能記錄自己的成長軌跡,歡迎大家指點。