首发于极光日报
聊聊 Android StateListAnimator

聊聊 Android StateListAnimator

简评:使用 StateListAnimator 轻松实现 Material Design 效果。

Material Design 中最基础的一条原则就是 'motion provides meaning',也就是当用户和你的 app 交互时应当提供合理的视觉反馈。标准做法是使用官方提供的 StateListDrawable 来为控件实现交互效果。

StateListAnimator 是和 Material Design 一同在 API 21 引入的,可以用来方便的实现交互反馈的视觉效果,今天这篇文章就讲解了 StateListAnimator 的用法。


在以前,我们处理 Button,TextView 等控件的点击效果时,通常是定义一个 selector,为按下和普通情况分别设置颜色。但这样的效果一方面不够动人,另一方面也不符合 Material Design 的

规范

Material Design 规范推荐 Button 等控件应当以材质的方式表现,当接触到手指时上升。因此 Material Design 对组件有了 z 轴这个概念,也就是高度。z 值越大,组件离界面底层(水平面)越远,投影越重。

那我们怎么来实现组件在 z 轴(高度)上的变化效果呢?这就需要用到今天讲到的 StateListAnimator 了。

首先,让我们创建一个 animator 资源文件夹,在其中创建一个 selector_animator.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true">
    <set>
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="scaleX"
        android:valueTo="1.025"
        android:valueType="floatType" />
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="scaleY"
        android:valueTo="1.025"
        android:valueType="floatType" />
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="translationZ"
        android:valueTo="4dp"
        android:valueType="floatType" />
    </set>
  </item>
 
  <item>
    <set>
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="scaleX"
        android:valueTo="1.0"
        android:valueType="floatType" />
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="scaleY"
        android:valueTo="1.0"
        android:valueType="floatType" />
      <objectAnimator
        android:duration="@android:integer/config_shortAnimTime"
        android:propertyName="translationZ"
        android:valueTo="0dp"
        android:valueType="floatType" />
    </set>
  </item>
 </selector>

代码很简单,当处于按下情况时,组件沿 x, y 轴扩大 1.025 倍并升高 4dp(会在组件四周产生投影效果)。

需要注意其中的 propertyName 属性目前支持:

  • translationX, translationY: 控制组件沿 x 和 y 轴移动多少距离。
  • rotation, rotationX, rotationY: 绕中心点旋转,设置 rotation 是 2D 平面旋转,rotationX 和 rotationY 分别是从屏幕内向屏幕外旋转和从左到右旋转,均为 3D 旋转。
  • scaleX, scaleY: 沿 x, y 轴的缩放比例,设置为 1.5 即 1.5 倍。
  • pivotX, pivotY: 设置组件的中心点在哪里,scale 和 rotation 都会根据设置的中心点来变化,默认为几何中心。
  • x, y: 组件最终要出现在相对其父容器的位置。
  • alpha: 组件的透明度,值的范围从 0 到 1,为 0 时完全透明。

然后在 layout 文件中设置组件的 stateListAnimator 值就可以啦:

<TextView
  android:id="@+id/textView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  ...  
  android:stateListAnimator="@animator/selector_animator" />

因为知乎不支持 gif,感兴趣的同学可以点击原文链接查看实现效果。

原文:StateListAnimator

相关阅读

欢迎关注:知乎专栏「极光日报」,每天为 Makers 导读三篇优质英文文章。

编辑于 2017-03-09 10:16