StateListAnimator 详解与使用方法
StateListAnimator 是 Android API 21 (Lollipop) 引入的强大动画框架组件,它可以根据视图的状态变化自动触发相应的动画效果。下面我将详细介绍其核心用法和工作原理。
1、基础概念
1.1、本质特性
状态驱动:根据 View 的状态(如 pressed/focused/enabled)切换动画
属性动画:底层使用 ObjectAnimator 修改视图属性
性能优化:相比传统的 Selector + AnimationSet 方案更高效
1.2、常用动画属性
属性名称 描述 示例值
translationZ Z轴位移(阴影效果) 8dp
scaleX/scaleY 缩放 0.9 / 1.2
rotation 旋转角度 15
alpha 透明度 0.7
2、基础用法示例
2.1、XML 定义(推荐)
<!-- res/animator/btn_state_animator.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 按下状态 -->
<item android:state_pressed="true">
<set>
<objectAnimator
android:propertyName="scaleX"
android:duration="50"
android:valueTo="0.92"/>
<objectAnimator
android:propertyName="scaleY"
android:duration="50"
android:valueTo="0.92"/>
<objectAnimator
android:propertyName="translationZ"
android:duration="50"
android:valueTo="4dp"/>
</set>
</item>
<!-- 默认状态 -->
<item>
<set>
<objectAnimator
android:propertyName="scaleX"
android:duration="100"
android:valueTo="1.0"/>
<objectAnimator
android:propertyName="scaleY"
android:duration="100"
android:valueTo="1.0"/>
<objectAnimator
android:propertyName="translationZ"
android:duration="100"
android:valueTo="0dp"/>
</set>
</item>
</selector>
2.2、应用到视图
<Button
android:layout_width="wrap_content"
android:layout_height="48dp"
android:text="Animated Button"
android:stateListAnimator="@animator/btn_state_animator"/>
3、支持的视图状态
完整的状态列表:
<item android:state_pressed=["true" | "false"]/>
<item android:state_focused=["true" | "false"]/>
<item android:state_selected=["true" | "false"]/>
<item android:state_checkable=["true" | "false"]/>
<item android:state_checked=["true" | "false"]/>
<item android:state_enabled=["true" | "false"]/>
<item android:state_hovered=["true" | "false"]/>
<item android:state_activated=["true" | "false"]/>
组合状态示例:
<item android:state_pressed="true" android:state_enabled="true">
<!-- 启用的按下状态动画 -->
</item>
4、动态设置方法
Java/Kotlin 代码控制:
// Kotlin 示例
val animator = AnimatorInflater.loadStateListAnimator(context, R.animator.btn_state_animator)
myButton.stateListAnimator = animator
// 清除动画
myButton.stateListAnimator = null
5、与 Material Design 组件的集成
对于 MaterialButton 等组件可以配合使用:
<style name="MyMaterialButton" parent="Widget.MaterialComponents.Button">
<item name="android:stateListAnimator">@animator/mtrl_btn_state_list_anim</item>
</style>
预置的 Material 动画资源位于: res/animator/mtrl_btn_state_list_anim.xml
6、性能优化建议
减少动画数量:单个 StateListAnimator 最多包含 3-4 个 objectAnimator
简化插值器:优先使用线性或快速进出插值器
短时长原则:交互动画建议持续 50-200ms
复用动画资源:相同效果的动画应该全局共用
7、常见问题解决
Q1:为什么动画不生效?
检查 API 等级 ≥ 21
确认没有其他代码覆盖了 stateListAnimator
查看是否设置了 android:clickable="false"
Q2:如何与 RippleDrawable 共存?
<!-- 波纹在前景层 -->
<Button
...
android:foreground="?attr/selectableItemBackgroundBorderless"
android:stateListAnimator="@animator/custom_anim"/>
掌握 StateListAnimator 可以让应用交互动画更加流畅自然,建议在实际项目中多加实践。