Android Material Button 能否设置类似ProgressBar的旋转图标作为内置图标?
可以实现,不需要自定义按钮控件,依托Material Components的原生API即可完成,以下是两种常用的落地方式:
方案1:使用AnimatedVectorDrawable实现(推荐)
这种方式和系统ProgressBar的动画效果一致,适配性最高:
- 首先在
res/drawable目录下创建旋转动画的矢量图资源ic_loading_circle.xml,示例代码如下:
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/ic_baseline_progress_circle_24"> <target android:name="rotationGroup" android:animation="@anim/rotate_360" /> </animated-vector>
- 配套的旋转动画
res/anim/rotate_360.xml代码:
<rotate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1200" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:repeatCount="infinite" android:toDegrees="360" />
- 需要切换加载状态时,直接给Material Button的
icon属性赋值上述动画资源,启动动画即可,示例代码(Kotlin):
// 切换为加载状态 val loadingAnim = ContextCompat.getDrawable(context, R.drawable.ic_loading_circle) as AnimatedVectorDrawable btnSubmit.apply { // 保存原有状态用于后续恢复 tag = Pair(text, icon) text = "提交中" icon = loadingAnim isEnabled = false // 加载时禁止点击 loadingAnim.start() } // 恢复普通状态 loadingAnim.stop() btnSubmit.apply { val (originText, originIcon) = tag as Pair<CharSequence, Drawable?> text = originText icon = originIcon isEnabled = true }
方案2:使用属性动画直接旋转按钮原有icon
如果不想额外创建动画资源,可以直接对Material Button的icon做旋转动画:
val rotateAnim = ObjectAnimator.ofFloat(btnSubmit.icon, View.ROTATION, 0f, 360f).apply { duration = 1200 repeatCount = ValueAnimator.INFINITE interpolator = LinearInterpolator() } // 加载时启动动画 rotateAnim.start() // 加载结束停止动画 rotateAnim.cancel()
注意事项
- 加载状态下建议禁用按钮点击,避免重复提交
- 页面销毁时要停止动画,避免内存泄漏
- 可以通过
iconGravity属性调整加载图标的位置,和文字居中对齐
内容的提问来源于stack exchange,提问作者Sharas
相关产品推荐
相关产品推荐

