1.xml文件
在res目錄下建一個(gè)anim文件夾,在文件夾中創(chuàng)建一個(gè)“frame.xml”格式文件
<?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="200" />
<item android:drawable="@drawable/b" android:duration="200" />
<item android:drawable="@drawable/c" android:duration="200" />
</animation-list>
duration屬性是在此幀停留的毫秒值
oneshot屬性表示是否只播放一次
用ImageView來(lái)播放幀動(dòng)畫(huà)
<ImageView
android:id="@+id/_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/frame" />
代碼中獲取動(dòng)畫(huà)并開(kāi)啟
ImageView iv= (ImageView) findViewById(R.id.iv);
AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
anim.start();
//anim.stop();
也可以在代碼中給控件設(shè)置動(dòng)畫(huà)
iv.setBackgroundResource(R.anim.frame);
2.代碼創(chuàng)建幀動(dòng)畫(huà)
ImageView iv= (ImageView) findViewById(R.id.iv);
AnimationDrawable anim= new AnimationDrawable();
//第一個(gè)參數(shù)是Drawable實(shí)例 第二個(gè)參數(shù)是毫秒值
anim.addFrame(getResources().getDrawable(R.drawable.img1), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img2), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img3), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img4), 200);
// 設(shè)置是否播放一次 true為播放一次
anim.setOneShot(false);
iv.setBackgroundDrawable(frameAnim);
anim.start();
以上是幀動(dòng)畫(huà)的兩種實(shí)現(xiàn)方式
PS.長(zhǎng)時(shí)間不用的東西真的容易忘啊
另外添加點(diǎn)東西,幀動(dòng)畫(huà)沒(méi)有監(jiān)聽(tīng)播放結(jié)束的回調(diào)接口,當(dāng)有這方面需求時(shí)就需要自己想辦法處理了
//獲取動(dòng)畫(huà)運(yùn)行時(shí)長(zhǎng),然后執(zhí)行下步操作
AnimationDrawable an =(AnimationDrawable)imageView.getBackground();
animationDrawable.start();
int duration = 0;
for(int i=0;i<an .getNumberOfFrames();i++){
duration += an .getDuration(i);
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//此處進(jìn)行下一步
}
}, duration);
釋放AnimationDrawable內(nèi)存
for (int i = 0; i < an .getNumberOfFrames(); i++) {
Drawable frame = an .getFrame(i);
if (frame instanceof BitmapDrawable) {
((BitmapDrawable) frame).getBitmap().recycle();
}
frame.setCallback(null);
}
an .setCallback(null);