通過定義一系列的drawable對象來創(chuàng)建一個幀動畫贫堰,被用于一個視圖的背景还栓。
創(chuàng)建幀動畫最簡單的方式是定義一個XML的動畫文件牙寞,放res/drawable/目錄下并將其設(shè)置為一個視圖對象的背景另患,然后調(diào)用start()方法運行動畫盏袄。
一個幀動畫的XML文件有一個<animation-list>和一系列內(nèi)嵌的<item>標簽組成。每一項定義一幀動畫葱她,如下:
spin_animation.xml file in res/drawable/ folder:
<animation-list android id="@+id/selected" android oneshot="false">
???? <item android:drawable="@drawable/wheel0" duration="100"/>
???? <item android:drawable="@drawable/wheel1" duration="100"/>
???? <item android:drawable="@drawable/wheel2" duration="100"/>
???? <item android:deawable="@drawable/wheel3" duration="100"/>
</animation-list>
注:
oneshot:為true時動畫將只運行一次后就停止撩扒;為false動畫將不停循環(huán);
drawable:設(shè)置每幀動畫顯示的內(nèi)容吨些;
duration:設(shè)置每幀的顯示時長搓谆,毫秒。
variablePadding:如果為true,允許drawable的padding根據(jù)當前的選擇狀態(tài)改變豪墅。
visible:提供drawable的初始可見狀態(tài)泉手,默認為false。
加載動畫的代碼:
ImageViewimg=(ImageView)findViewById(R.id.spinning_wheel_image);
img.setBackgroundResource(R.drawable.spin_animation);
AnimationDrawableframeAnimation=(AnimationDrawable)img.getBackground();
frameAnimation.start();
更多:
It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window.(來自官方文檔)
在Activity的onCreate()方法中不能調(diào)用幀動畫的start()方法偶器,因為幀動畫尚未完全的加載到窗口上斩萌。你可以在Activity的onWindowFouseChanged()方法中調(diào)用動畫。
但是:
如果在布局中給ImageView設(shè)置背景:
android:background="@drawable/spin_animation"
然后在Activity的onCreate()方法中調(diào)用:
ImageViewimg=(ImageView)findViewById(R.id.spinning_wheel_image);
AnimationDrawableframeAnimation=(AnimationDrawable)img.getBackground();
frameAnimation.start();
上述情況是可行的屏轰。
??????????????