我想将一个动画列表添加到选择器xml文件中,然后将其添加到ImageButton中。在默认状态下,我希望播放动画并按下状态,我想要显示其他图像。我的代码正在处理按钮状态更改,但动画在默认状态下无效。 其实我正在阅读Android
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"/>
答案 0 :(得分:1)
只需drawable
背景动画即可:
ImageButton imageButton = (ImageButton) findViewById(R.id.button_infect);
imageButton.setBackgroundResource(R.drawable.anim_virus);
如果您想.start()
动画,请执行以下操作:
((AnimationDrawable) imageButton.getBackground()).start();
如果你想要.stop()
,请执行以下操作:
((AnimationDrawable) imageButton.getBackground()).stop();
但是,要从StateListDrawable
获取ImageButton
动画,您已将StateListDrawable
设置为XML中的android:background
属性。
StateListDrawable background = (StateListDrawable) imageButton.getBackground();
Drawable current = background.getCurrent();
if (current instanceof AnimationDrawable) {
imageButton = (AnimationDrawable) current;
btnAnimation.start();
}
因此,此代码从ImageButton
获取背景,然后根据您所处的状态将背景定义为drawable
。如果当前状态为instanceof AnimationDrawable
即你的animation-list
然后它会播放动画。
修改:已从评论中的错误更改
E / AndroidRuntime:FATAL EXCEPTION:main进程:java.lang.RuntimeException:无法启动活动ComponentInfo {AttackPlanetActivity}:java.lang.ClassCastException:android.graphics.drawable.StateListDrawable无法强制转换为android.graphics.drawable .AnimationDrawable在android.app.ActivityThread.performLaunchActivity
信用编辑:Button states with Background as AnimationDrawable in Android