I have created custom buttons in Android for a while. Everything was simple, just made image resources for button states and made a selector for it. Everything went smoothly and pleasantly. Now I am faced with a new situation. I created an animation and set it as the background for my button.
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> <item android:drawable="@drawable/frame1" android:duration="600" /> <item android:drawable="@drawable/frame2" android:duration="300" /> <item android:drawable="@drawable/frame3" android:duration="500" /> </animation-list>
If I set up the animation as the Background button, it works fine. If I try to make a simple selector
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false" android:drawable="@drawable/animation" /> <item android:state_pressed="true" android:drawable="@drawable/pressed" /> </selector>
where the normal state of the button will have animation as a background, and pressing it will be a static image, everything does not work correctly.
In my main activity, on onWindowFocus, I get the button background and start the animation
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); btn = (Button)findViewById(R.id.btnAnim); btnAnimation = (AnimationDrawable) btnAnim.getBackground(); btnAnimation.start(); }
There seems to be a problem here, because my animation will not be correctly selected from the selector, and I get the following error:
03-14 15:21:16.146: ERROR/AndroidRuntime(440): FATAL EXCEPTION: main 03-14 15:21:16.146: ERROR/AndroidRuntime(440): java.lang.ClassCastException: android.graphics.drawable.StateListDrawable 03-14 15:21:16.146: ERROR/AndroidRuntime(440): at com.bebenjoy.MainActivity.onWindowFocusChanged(MainActivity.java:53) 03-14 15:21:16.146: ERROR/AndroidRuntime(440): at ...
Any idea on how to fix this? Thanks.
Alin
source share