<objectAnimator>和ValueAnimator aka <animator>之间的区别是什么?

7
我开始学习安卓上的动画,阅读https://developer.android.com/guide/topics/resources/animation-resource.html。我发现有两个XML元素和ValueAnimator aka。前者用于动画化对象属性,但对链接页面所提供的定义感到困惑。定义如下:“在指定的时间内执行动画。表示一个ValueAnimator”。这两个标签具有相同的属性:
    <objectAnimator
    android:propertyName="string"
    android:duration="int"
    android:valueFrom="float | int | color"
    android:valueTo="float | int | color"
    android:startOffset="int"
    android:repeatCount="int"
    android:repeatMode=["repeat" | "reverse"]
    android:valueType=["intType" | "floatType"]/>

<animator
    android:duration="int"
    android:valueFrom="float | int | color"
    android:valueTo="float | int | color"
    android:startOffset="int"
    android:repeatCount="int"
    android:repeatMode=["repeat" | "reverse"]
    android:valueType=["intType" | "floatType"]/>

有人能解释一下它们的区别以及何时使用什么吗?任何答案和评论都将不胜感激。

1个回答

27

ObjectAnimator是ValueAnimator的子类,主要区别在于在ValueAnimator中,您必须重写onAnimationUpdate(...)方法,在其中指定动画值应用的位置:

ObjectAnimator是ValueAnimator的一个子类。其主要的不同之处在于,在ValueAnimator中你需要重写onAnimationUpdate(...)方法,并在其中指定动画值的应用位置。

ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator animation) {
       view.setAlpha((Float) animation.getAnimatedValue());
   }
});
animator.start();

ObjectAnimator 将独立处理此问题:

ObjectAnimator.ofFloat(view, View.ALPHA, 0, 1).start();

在处理XML时,请注意objectAnimator的"propertyName",而该属性标签中没有animator标签。

另外,从API 23开始,您还可以同时对多个属性进行动画处理:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
                android:duration="1000"
                android:repeatCount="1"
                android:repeatMode="reverse">
    <propertyValuesHolder android:propertyName="x" android:valueTo="400"/>
    <propertyValuesHolder android:propertyName="y" android:valueTo="200"/>
</objectAnimator>

并/或自定义动画帧:

<animator xmlns:android="http://schemas.android.com/apk/res/android"
          android:duration="1000"
          android:repeatCount="1"
          android:repeatMode="reverse">
    <propertyValuesHolder>
        <keyframe android:fraction="0" android:value="1"/>
        <keyframe android:fraction=".2" android:value=".4"/>
        <keyframe android:fraction="1" android:value="0"/>
    </propertyValuesHolder>
</animator>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接