Animator is for Interactive animation. In general, we use animation like this:
But here if we add an onClick listener. We will find, clicking on the new location where the view is located currently doesn’t work! But clicking on the previous location works?!
It is because Animation only redraws UI. But the response location won’t change. So it’s not fit with interactive animation.
So to make better interactive animation, we have now two animators after 3.0:
ValueAnimator
It provides a simple timing engine for running animations which calculate animated values and set them on target objects. ValueAnimator itself does not act on any of properties nor provide any animation. It is just a single timing pulse that all animations use (We could also use it for other things). It runs in a custom handler to ensure that property changes happen on the UI thread.
By default, ValueAnimator uses non-linear time interpolation, via the AccelerateDecelerateInterpolator class, which accelerates into and decelerates out of an animation. This behavior can be changed by calling setInterpolator(TimeInterpolator).
ObjectAnimator
To animate a property of target object. It needs Get/Set functions for this property. More details, this subclass of ValueAnimator provides support for animating properties on target objects. The constructors of this class take parameters to define the target object that will be animated as well as the name of the property that will be animated. Appropriate set/get functions are then determined internally and the animation will call these functions as necessary to animate the property.
How to use ObjectAnimator
But we will see here, all actions run in the mean time beacasue start() is asynchronous. So here we could use PropertyValuesHolder and AnimatorSet to control animators to run.
PropertyValuesHolder
AnimatorSet
AnimatorSet is more powful:
Set Listener
Two ways:
new Animator.AnimatorListener() - need to override all the functions
new AnimatorListenerAdapter() - only need to override the functions we want
How to use ValueAnimator
ValueAnimator for Object
With ValueAnimator.ofObject. ValueAnimator will calculate a time factor between 0 and 1 (animation current time / animation totle time). So we could use it to set specific property animation for each frame.
The idea is that the float fraction determines the position at which to interpolate.
When fraction is 0.0 then evaluate should return the start value.
When fraction is 1.0 then it should return the end value.
For any number between 0.0 and 1.0, it should return an object that lies somewhere between the start value and the end value.