如何实现右侧带动画的Drawable按钮?现有代码运行崩溃该如何解决?
问题原因
你总共犯了3个核心错误,直接对应报错信息里的异常:
- drawable目录下的
<rotate>标签属于RotateDrawable,规则要求必须指定android:drawable属性绑定要旋转的图片资源,你没加这个属性就是本次报错的直接触发原因;如果是视图动画的<rotate>标签需要放在res/anim/目录下,不能放在drawable目录。 - 复合Drawable索引取值错误:
setCompoundDrawablesWithIntrinsicBounds的参数顺序是「左、上、右、下」,你设置的是右侧图标,对应getCompoundDrawables()返回数组的索引是2而非0,取sb[0]会拿到空对象,后续操作直接崩溃。 - 类型强转错误:
AnimationDrawable是帧动画的实现类,你写的旋转动画不属于帧动画,强转会抛出类型转换异常。
修复方案(二选一即可)
方案1:使用AnimatedRotateDrawable(Drawable动画,推荐)
- 将
button_spin_animation.xml放在res/drawable目录下,修改内容如下:
<?xml version="1.0" encoding="utf-8"?> <animated-rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@mipmap/你要旋转的图标资源名" android:fromDegrees="0" android:toDegrees="360" android:pivotX="50%" android:pivotY="50%" android:repeatCount="infinite" />
- 修改调用代码:
@Override public void onStart() { super.onStart(); account_login.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getApplicationContext(), R.drawable.button_spin_animation), null); Drawable[] sb = account_login.getCompoundDrawables(); // 右侧图标对应索引2,用AnimatedRotateDrawable接收 AnimatedRotateDrawable animDrawable = (AnimatedRotateDrawable) sb[2]; animDrawable.start(); }
方案2:使用视图动画
- 新建
res/anim目录,将button_spin_animation.xml移入该目录,内容不需要修改。 - 先给按钮设置右侧固定图标,再给图标加动画:
@Override public void onStart() { super.onStart(); // 先设置右侧要显示的图标 account_login.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getApplicationContext(), R.mipmap.你要旋转的图标资源名), null); // 加载动画 Animation rotateAnim = AnimationUtils.loadAnimation(this, R.anim.button_spin_animation); // 启动动画 account_login.getCompoundDrawables()[2].startAnimation(rotateAnim); }
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

