最近在實(shí)現(xiàn)一個button的效果時宴咧,UI要求未點(diǎn)擊時根灯,button有相應(yīng)的動畫,按住時有相應(yīng)的效果掺栅,于是自然而然的想到了使用StateListDrawable 箱吕,以及幀動畫。
遇到了一個異常:android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.AnimationDrawable柿冲。
以下是我的相應(yīng)代碼:
xml中:
<Button android:id="@+id/setting_user_rank_id"
android:layout_width="@dimen/person_setting_user_rank_btn_width"
android:layout_height="@dimen/person_setting_user_rank_btn_height"
android:layout_marginRight="@dimen/person_setting_user_rank_btn_margin_right"
android:layout_marginTop="@dimen/person_setting_user_rank_btn_margin_top"
android:background="@drawable/person_setting_user_rank_style"
android:layout_alignParentRight="true"
android:onClick="onClick"/>
person_setting_user_rank_style.xml:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/person_setting_user_rank_pressed" android:state_pressed="true"/>
<item android:drawable="@anim/user_rank_btn_anim" android:state_focused="true"/>
<item android:drawable="@anim/user_rank_btn_anim" />
</selector>
res/anim/user_rank_btn_anim.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/user_rank_btn_bg_0" android:duration="125"></item>
<item android:drawable="@drawable/user_rank_btn_bg_1" android:duration="125"></item>
<item android:drawable="@drawable/user_rank_btn_bg_2" android:duration="125"></item>
<item android:drawable="@drawable/user_rank_btn_bg_3" android:duration="125"></item>
<item android:drawable="@drawable/user_rank_btn_bg_4" android:duration="125"></item>
</animation-list>
一開始在activity中是直接調(diào)用了:
mUserRankAnim= (AnimationDrawable) mUserRankBtn.getBackground();
mUserRankAnim.start();
結(jié)果出現(xiàn)了:
android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.AnimationDrawable異常茬高。
由于button的android:background采用的是StateListDrawable ,那么mUserRankBtn.getBackground()得到的也就會是StateListDrawable 假抄,而不是AnimationDrawable怎栽,所以會出現(xiàn)這個異常。
正確的寫法是:
private void startUserRankAnim() {
//讓按鈕獲取到焦點(diǎn)(為了進(jìn)入activity后自動開始動畫宿饱,如果是點(diǎn)擊button后才開始動畫熏瞄,那么可以不用獲取焦點(diǎn))
mUserRankBtn.setFocusable(true);
mUserRankBtn.setFocusableInTouchMode(true);
mUserRankBtn.requestFocus();
mUserRankBtn.requestFocusFromTouch();
StateListDrawable background = (StateListDrawable) mUserRankBtn.getBackground();
Drawable current = background.getCurrent();
if (current instanceof AnimationDrawable) {
mUserRankAnim = (AnimationDrawable) current;
mUserRankAnim.start();
}
}