如何使用StateListAnimator?

nha*_*man 21 android android-5.0-lollipop

来自文档:

新的StateListAnimator类允许您定义在视图状态更改时运行的动画制作器.以下示例显示如何将StateListAnimator定义为XML资源:

<!-- animate the translationZ property of a view when pressed --> <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  <item android:state_pressed="true">
    <set>
      <objectAnimator android:propertyName="translationZ"
        android:duration="100"
        android:valueTo="2"
        android:valueType="floatType"/>
        <!-- you could have other objectAnimator elements
             here for "x" and "y", or other properties -->
    </set>   
  </item>   
  <item android:state_enabled="true"
    android:state_pressed="false"
    android:state_focused="true">
    <set>
      <objectAnimator android:propertyName="translationZ"
        android:duration="100"
        android:valueTo="2"
        android:valueType="floatType"/>
    </set> 
  </item> 
</selector>
Run Code Online (Sandbox Code Playgroud)

但是,它没有说明如何实际使用此xml文件.在类上似乎没有方法Resources来获取a StateListAnimator,并且StateListAnimator类也没有提供任何信息.

我们怎么用呢?

har*_*ism 25

Android L中,View添加了一个新的xml属性:

android:stateListAnimator   : Sets the state-based animator for the View.
Run Code Online (Sandbox Code Playgroud)

另外,以编程方式实例化StateListAnimator对象的新方法:

loadStateListAnimator(Context context, int id)
Run Code Online (Sandbox Code Playgroud)

已被添加到AnimatorInflater.

这些可以在Android L开发人员预览文档包中找到.

  • 对于代码段,请尝试StateListAnimator sla = AnimatorInflater.loadStateListAnimator(context,R.anim.my_anim); View.setStateListAnimator(SLA); (11认同)

Rad*_*esh 5

我在Java中使用此代码,效果很好

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            crd.setStateListAnimator(AnimatorInflater.loadStateListAnimator(ctx,
                    R.drawable.card_smooth_shadow));
}
Run Code Online (Sandbox Code Playgroud)

还有我的动画师/card_smooth_shadow.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:propertyName="translationZ"
            android:duration="@android:integer/config_shortAnimTime"
            android:valueTo="10dp"
            android:valueType="floatType"/>
    </set>
</item>
<item
    android:state_pressed="false">
    <set>
        <objectAnimator android:propertyName="translationZ"
            android:duration="100"
            android:valueTo="2dp"
            android:valueType="floatType"/>
    </set>
</item>
Run Code Online (Sandbox Code Playgroud)

结果

结果