我想將動畫列表添加到選擇器xml文件,然後將其添加到ImageButton中。在默認狀態下,我想要播放動畫並按下狀態,我想要顯示其他圖像。我的代碼正在爲按鈕狀態更改工作,但動畫在默認狀態下不起作用。 其實我讀的Android如何將幀動畫添加到ImageButton,包括按鈕狀態更改處理?
anim_virus.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/attackvirus0" android:duration="50" />
<item android:drawable="@drawable/attackvirus1" android:duration="50" />
<item android:drawable="@drawable/attackvirus2" android:duration="50" />
<item android:drawable="@drawable/attackvirus3" android:duration="50" />
<item android:drawable="@drawable/attackvirus4" android:duration="50" />
<item android:drawable="@drawable/attackvirus5" android:duration="50" />
<item android:drawable="@drawable/attackvirus4" android:duration="50" />
<item android:drawable="@drawable/attackvirus3" android:duration="50" />
<item android:drawable="@drawable/attackvirus2" android:duration="50" />
<item android:drawable="@drawable/attackvirus1" android:duration="50" />
</animation-list>
button_state_virus.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/attackviruspress"/>
<item android:state_focused="true" android:drawable="@drawable/attackvirusfocus"/>
<item android:drawable="@drawable/anim_virus" android:state_enabled="true"/>
</selector>
我的圖片按鈕,標籤和它的參數是:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_margin="10dp"
android:soundEffectsEnabled="true"
android:src="@drawable/button_state_virus"
android:id="@+id/button_infect"
android:contentDescription="@string/content_desc_virus"/>
我曾嘗試使用AnimationDrawable,就像你提到的。但它會導致應用程序崩潰,錯誤描述爲'E/AndroidRuntime:FATAL EXCEPTION:main Process:java.lang.RuntimeException:無法啓動活動ComponentInfo {AttackPlanetActivity}:java.lang.ClassCastException:android.graphics.drawable.StateListDrawable can not在android.app.ActivityThread.performLaunchActivity'上投射到android.graphics.drawable.AnimationDrawable。如果我將anim_virus設置爲按鈕並刪除android:src參數,則可以使用AnimationDrawable start() –
檢查新的編輯預覽。 –