Button 默認圖 A,點擊後循環播放圖 B→C→D,再次點擊恢復圖 A。
res/drawable/btn_anim.xml 定義幂動畫:
<animation-list xmlns:android="..." android:oneshot="false">
<item android:drawable="@drawable/img_b" android:duration="200"/>
<item android:drawable="@drawable/img_c" android:duration="200"/>
<item android:drawable="@drawable/img_d" android:duration="200"/>
</animation-list>
AnimationDrawable anim = (AnimationDrawable) btn.getBackground();
btn.setOnClickListener(v -> {
if (anim.isRunning()) {
anim.stop();
btn.setBackgroundResource(R.drawable.img_a); // 恢復默認
} else {
btn.setBackgroundResource(R.drawable.btn_anim);
anim = (AnimationDrawable) btn.getBackground();
anim.start();
}
});