一、场景介绍
在 Android 中,要为视图状态变更添加动画效果(比如:Button、RadioButton状态变更),可以通过 StateListAnimator 类来实现,只需要一个 XML 动画资源文件,仅用一张图片资源就可以实现点击效果,简单易用。
StateListAnimator可以定义一系列的动画,这些动画将会根据关联的View的状态变更而进行动画切换。
二、使用介绍
StateListAnimator 可以在 XML 资源中定义,以 <selector> 元素为根节点,每一个状态的动画用一个<item> 元素定义,在 <item> 元素内部定义 AnimatorSet 或者 OjbectAnimator,或者在 <item> 元素中通过 android:animation 属性引用已有的动画资源。
- 示例代码
res/animator/selector_animate_scale.xml(官方文档说放在 res/xml 目录下,但笔者发现放在该目录下编辑不会有自动补全提示,而放在 res/animator 目录下编辑时是可以自动补全提示,而且能够正常引用)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 按下状态,X和Y缩放到110% -->
<item android:state_pressed="true">
<set>
<objectAnimator android:propertyName="scaleX"
android:duration="300"
android:valueTo="1.1"
android:valueType="floatType"/>
<objectAnimator android:propertyName="scaleY"
android:duration="300"
android:valueTo="1.1"
android:valueType="floatType"/>
</set>
</item>
<!-- 正常状态,X和Y缩放到100% -->
<item>
<set>
<objectAnimator android:propertyName="scaleX"
android:duration="300"
android:valueTo="1"
android:valueType="floatType"/>
<objectAnimator android:propertyName="scaleY"
android:duration="300"
android:valueTo="1"
android:valueType="floatType"/>
</set>
</item>
</selector>
在布局中使用 android:stateListAnimator 属性为 View 添加 StateListeAnimator
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
android:minHeight="200dp"
android:src="@mipmap/ic_launcher"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnShow"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:clickable="true"
android:stateListAnimator="@animator/selector_animate_scale"/>
注意事项:
StateListAnimator需要和视图绑定,除了可以在 XML中进行绑定之外,也可以在代码中通过AnimatorInflater.loadStateListAnimator()方法加载StateListAnimator,然后使用View.setStateListAnimator()方法将Animator绑定到对应的视图。
- 效果

三、编后语
通过 StateListAnimator 实现在视图状态发生变化时的动画,可以提高用户体验,而且在一定程度上减少资源图片。
上一篇:Android 属性动画(一)新手入门
下一篇:Android 属性动画(三)使用类型评估程序–TypeEvaluate
本文介绍如何使用StateListAnimator为Android视图状态变更添加动画效果。通过一个实例展示了如何定义XML动画资源文件,并在布局文件中应用它。文章还提供了一些注意事项,帮助开发者更好地理解和运用StateListAnimator。
2967

被折叠的 条评论
为什么被折叠?



