根据您的视图如何获得其背景颜色以及您如何获得目标颜色,有几种不同的方法可以做到这一点。
前两个使用Android Property Animation 框架。
在以下情况下使用Object Animator:
- 您的视图将其背景颜色定义为 xml 文件中的
argb 值。
- 您的视图之前的颜色由
view.setBackgroundColor() 设置
- 您的视图在可绘制对象中定义了其背景颜色,不定义了任何额外的属性,例如描边或角半径。
- 您的视图在可绘制对象中定义了其背景颜色,并且您想要删除任何额外的属性,例如笔划或角半径,请记住,额外属性的删除不会动画。
对象动画师通过调用view.setBackgroundColor 来工作,它会替换定义的可绘制对象,除非它是ColorDrawable 的实例,它很少是。这意味着来自可绘制对象的任何额外背景属性(如笔划或角)都将被删除。
在以下情况下使用Value Animator:
- 您的视图在可绘制对象中定义了其背景颜色,该可绘制对象还设置了笔划或角半径等属性,并且您希望将其更改为运行时确定的新颜色。
在以下情况下使用Transition drawable:
- 您的视图应在部署前已定义的两个可绘制对象之间切换。
我在打开一个我无法解决的 DrawerLayout 时运行的 Transition drawables 遇到了一些性能问题,所以如果您遇到任何意外的卡顿,您可能会遇到与我相同的错误。
如果您想使用StateLists drawable 或LayerLists drawable,则必须修改Value Animator 示例,否则它将在final GradientDrawable background = (GradientDrawable) view.getBackground(); 行上崩溃。
Object Animator:
查看定义:
<View
android:background="#FFFF0000"
android:layout_width="50dp"
android:layout_height="50dp"/>
像这样创建和使用ObjectAnimator。
final ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(view,
"backgroundColor",
new ArgbEvaluator(),
0xFFFFFFFF,
0xff78c5f9);
backgroundColorAnimator.setDuration(300);
backgroundColorAnimator.start();
您还可以使用 AnimatorInflater 从 xml 加载动画定义,就像 XMight 在 Android objectAnimator animate backgroundColor of Layout 中所做的那样
Value Animator:
查看定义:
<View
android:background="@drawable/example"
android:layout_width="50dp"
android:layout_height="50dp"/>
可绘制定义:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:color="#edf0f6"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
像这样创建和使用 ValueAnimator:
final ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(),
0xFFFFFFFF,
0xff78c5f9);
final GradientDrawable background = (GradientDrawable) view.getBackground();
currentAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(final ValueAnimator animator) {
background.setColor((Integer) animator.getAnimatedValue());
}
});
currentAnimation.setDuration(300);
currentAnimation.start();
Transition drawable:
查看定义:
<View
android:background="@drawable/example"
android:layout_width="50dp"
android:layout_height="50dp"/>
可绘制定义:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="#FFFFFF"/>
<stroke
android:color="#edf0f6"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
</item>
<item>
<shape>
<solid android:color="#78c5f9"/>
<stroke
android:color="#68aff4"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
</item>
</transition>
像这样使用 TransitionDrawable:
final TransitionDrawable background = (TransitionDrawable) view.getBackground();
background.startTransition(300);
您可以通过在动画实例上调用.reverse() 来反转动画。
还有其他一些制作动画的方法,但这三种可能是最常见的。我通常使用 ValueAnimator。