How do you animate the change of background color of a view on Android?
For example:
I have a view with a red background color. The background color of the view changes to blue. How can I do a smooth transition between colors?
If this can't be done with views, an alternative will be welcome.
Depending on how your view gets its background color and how you get your target color there are several different ways to do this.
The first two uses the Android Property Animation framework.
Use a Object Animator if:
argb
value in a xml file.view.setBackgroundColor()
The object animator works by calling
view.setBackgroundColor
which replaces the defined drawable unless is it an instance of aColorDrawable
, which it rarely is. This means that any extra background properties from a drawable like stroke or corners will be removed.Use a Value Animator if:
Use a Transition drawable if:
I have had some performance issues with Transition drawables that runs while I am opening a DrawerLayout that I haven't been able to solve, so if you encounter any unexpected stuttering you might have run into the same bug as I have.
You will have to modify the Value Animator example if you want to use a StateLists drawable or a LayerLists drawable, otherwise it will crash on the
final GradientDrawable background = (GradientDrawable) view.getBackground();
line.Object Animator:
View definition:
Create and use a
ObjectAnimator
like this.You can also load the animation definition from a xml using a AnimatorInflater like XMight does in Android objectAnimator animate backgroundColor of Layout
Value Animator:
View definition:
Drawable definition:
Create and use a ValueAnimator like this:
Transition drawable:
View definition:
Drawable definition:
Use the TransitionDrawable like this:
You can reverse the animations by calling
.reverse()
on the animation instance.There are some other ways to do animations but these three is probably the most common. I generally use a ValueAnimator.
Another easy way to achieve this is to perform a fade using AlphaAnimation.
best way is to use ValueAnimator and
ColorUtils.blendARGB
Answer is given in many ways. You can also use
ofArgb(startColor,endColor)
ofValueAnimator
.for API > 21:
You can make an object animator. For example, I have a targetView and I want to change your background color:
If you want color animation like this,
this code will help you: