Analysis of Android property Animation

Source: Internet
Author: User

Analysis of Android property Animation
As you can see, when developing a product, we can add some animation effects in the application to achieve a good user experience, such as translation, scaling, and rotation, however, these commonly used animations exist in early versions of Android. We call them traditional animations. Traditional animations are generally divided into Tween and Frame animations, which are our most commonly used animations, it is collectively referred to as Animation. The traditional Animation is implemented by repeatedly calling the onDraw method of the View to re-draw the View. After Android3.0, Google added the property animation framework Animator for Android. Why is it called property animation? Because the attribute animation Animator does not need to constantly call the onDraw method to draw the interface as traditional animations do, and you can use the get and set methods to actually change the attribute of a view. An Animation only gives you a "fake" Animation effect. Its Animation view does not change its attributes, such as its position. The attribute animation is a real and positive way to "Animation" the view to the specified position through code.
Traditional animations cannot change the actual view attributes. Let's take a look at the effects of traditional animations. We use a very simple interface to set up a flattened image for the specified ImageView and specify a click event listener for the ImageView, it is convenient for us to test the limitations of traditional animation.

Public class MainActivity extends Activity {private Button mButton; private ImageView mImageView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_main); mButton = (Button) findViewById (R. id. button); mImageView = (ImageView) findViewById (R. id. imageview); mButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {playAnim () ;}}); mImageView. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {showToast () ;}});}/*** playback animation */protected void playAnim () {TranslateAnimation ta = new TranslateAnimation (0.0f, 200366f, 0.0f, 0.0f); ta. setDuration (1, 1000); ta. setFillAfter (true); mImageView. startAnimation (ta);} protected void showToast () {Toast. makeText (MainActivity. this, Hello, Toast. LENGTH_SHORT ). show ();}}
We have set the click event for the ImageView robot and the Toast is displayed. When we click the Button, the translation animation on the ImageView is executed, and it is translated to the specified position (200px). However, when we click on the ImageView at this time, the Toast prompt is not displayed, that is, the clicked position is not there, when I click the original position of the ImageView again, Toast is displayed again. Is it strange "? Yes, the small example above shows that the traditional Animaion animation can only change the animation of the dynamic visual effect, and cannot actually change the attribute (location, etc.) of a View ). In addition, the traditional Animation is completed by constantly calling the onDraw method, which consumes resources (cpu.
API Overview
Class Description
ValueAnimator The property animation time series engine also calculates the property animation value. It has all the core functions, computes animation values, and contains each animation. Whether or not the detailed information about the time sequence is repeated, the listener receives update events, and sets the custom type of capability evaluation. There are two animated attributes: animation value calculation and property animation value setting for these objects. ValueAnimator does not take the second part, so you must update the calculated value ValueAnimator and modify the object you want to use your own logical animation.
ObjectAnimator The subclass of ValueAnimator allows you to set an animation for the target object and object attributes. When a new animation value is calculated, this class updates the corresponding attributes. You use ObjectAnimator in most cases, because it makes the value of the target object of the animation easier. However, sometimes you directly use ValueAnimator because ObjectAnimator has some limitations, such as the specific acessor method currently required for the target object.
AnimatorSet Provides a mechanism to combine animations for them to run in association. You can set an animation to play together, in sequence, or after a specified delay.
Content from: http://developer.android.com/guide/topics/graphics/prop-animation.html

In ObjectAnimator, when executing a single animation, we usually use the ObjectAnimator class to set an animation for our view. Let's take a simple look. After using the property animation, what changes will the ImageView take in the above small example? Modify the playAnim method above and replace the normal animation with the property Animation:
protected void playAnim() {ObjectAnimator.ofFloat(mImageView, translationX, 0.0f, 200.0f).setDuration(1000).start();}
Shows the running effect. Compared with the figure above, it is found that after the attribute animation is executed, not only the position of the ImageView is changed visually, but also the position of the click event on the ImageView is changed, it indicates that the View with attribute animation actually changes the attribute of a View. From the code above, we can find that attribute animation is very simple to use. The ofFloat method in ObjectAnimator is actually a static method, and the return value is still an ObjectAnimator object. The ofFloat parameter is also very simple. The first parameter is the view to be animated, the second parameter is the animation mode, and the third parameter is a variable array, here we need to describe the coordinates of the initial position and the end position of the animation. In addition to the translationX attribute in the preceding example, you can specify the translationY attribute to indicate that the ImageView is translated along the Y axis. Then, you can specify X or Y, the difference between translationX and X, or translationY and Y is that translationX specifies the offset of ImageView on the X axis. Simply specifying X indicates that ImageView is moved to the specified position on the X axis, this is similar to the scrollTo and scrollBy methods of View. In addition to translation, you can also specify the animation modes as follows: TranslationX and translationY Rotation, rotationX, and rotationY ScaleX, scaleY X, Y Alpha

ObjectAnimator inherits from ValueAnimator. You must specify an object and its attributes. When the calculation of the attribute value is complete, it is automatically set to the corresponding attribute of the object, this completes all two steps of Property Animation. In practice, ObjectAnimator is usually used to change a certain attribute of an object. However, ObjectAnimator has certain restrictions. To use ObjectAnimator, the following conditions must be met:

The object should have a setter function: set In the preceding example, for factory methods such as ofFloat, the first parameter is the object name, the second parameter is the attribute name, and the following parameter is a variable parameter. If values... If only one value is set for the parameter, it is assumed as the destination value. The change range of the attribute value is from the current value to the destination value. To obtain the current value, the object must have the getter method of the corresponding property: get If there is a getter method, the type of the response value should be the same as the parameter type of the corresponding setter method.

If the preceding conditions are not met, ObjectAnimator cannot be used instead of ValueAnimator.


When multiple animations execute PropertyValuesHolder at the same time, sometimes we need to execute the superposition of Multiple Attribute animations at the same time, we can use the PropertyValuesHolder tool class to "LOAD" multiple animations and then call ObjectAnimator. the ofPropertyValuesHolder () method submits the loaded animation to ObjectAnimator for execution. For example:
protected void playAnim() {PropertyValuesHolder p1 = PropertyValuesHolder.ofFloat(translationX,0.0f, 200.0f);PropertyValuesHolder p2 = PropertyValuesHolder.ofFloat(translationY,0.0f, 200.0f);PropertyValuesHolder p3 = PropertyValuesHolder.ofFloat(rotation,0.0f, 360.0f);ObjectAnimator.ofPropertyValuesHolder(mImageView, p1, p2, p3).setDuration(2000).start();}

Like a normal View animation, the animation set provides an animation set for you to execute multiple animation effects.
protected void playAnim() {Animator animator1 = ObjectAnimator.ofFloat(mImageView, translationX,0.0f, 200.0f);Animator animator2 = ObjectAnimator.ofFloat(mImageView, translationY,0.0f, 200.0f);Animator animator3 = ObjectAnimator.ofFloat(mImageView, rotation,0.0f, 360.0f);AnimatorSet set = new AnimatorSet();set.playTogether(animator1, animator2, animator3);set.setDuration(2000);set.start();}

AnimationSet provides a mechanism to combine multiple animations into one, and allows you to set the timing relationships of the animations in the group, such as simultaneous playback and sequential playback.

In the following example, five animations are applied simultaneously:

Play anim1; play anim2, anim3, anim4 at the same time; play anim5.
AnimatorSet bouncer = new AnimatorSet();bouncer.play(anim1).before(anim2);bouncer.play(anim2).with(anim3);bouncer.play(anim2).with(anim4)bouncer.play(anim5).after(amin2);animatorSet.start();

The Android property animation of the animation listening event also provides a listener for the animation playing process. We only need to call the Animator. addListener () method and pass the AnimatorListener object to it:
Anim. addListener (new Animator. animatorListener () {@ Overridepublic void onAnimationStart (Animator animation) {// execution at animation start} @ Overridepublic void onAnimationRepeat (Animator animation) {// execute when the animation is repeated} @ Overridepublic void onAnimationEnd (Animator animation) {// execute when the animation ends} @ Overridepublic void onAnimationCancel (Animator animation) {// executed when the animation is canceled }});
There are four unimplemented methods under the Animator. AnimatorListener object. We can implement the methods separately to conveniently listen to the animation execution process. However, the Animator. AnimatorListener object is not concise, because most of the time we only need to listen to the events at the end of the animation, Android also provides us with a simplified listening object, AnimatorListenerAdapter and AnimatorListenerAdapter.
Is an abstract class. There are several methods for calling onAnimationCancel (), onAnimationEnd (), onAnimationPause (), onAnimationRepeat (), onAnimationResume (), and onAnimationStart, since we generally only need to listen when the animation ends, we can use the following method:
anim.addListener(new AnimatorListenerAdapter() {@Overridepublic void onAnimationEnd(Animator animation) {// TODO Auto-generated method stubsuper.onAnimationEnd(animation);}});

ValueAnimator Concept

ValueAnimator includes all the core functions of the Property Animation, such as the Animation time, start and end attribute values, and the calculation method of the corresponding time attribute values. The application Property Animation has two steps:

Calculate the property value and perform corresponding actions based on the property value, such as modifying an object's property.

ValuAnimiator only completes Step 1. To complete step 2, you must implement ValueAnimator. onUpdateListener interface, which has only one function onAnimationUpdate (). In this function, ValueAnimator object is input as a parameter. The getAnimatedValue () function of the ValueAnimator object can obtain the current attribute value, for example:

 

protected void playAnim() {ValueAnimator animator = ValueAnimator.ofInt(0, 10);animator.setDuration(100);animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {@Overridepublic void onAnimationUpdate(ValueAnimator animation) {Log.i(TAG, AnimatedValue :  + animation.getAnimatedValue().toString());}});animator.start();}

 

From the above example, we can see that the ValueAnimator class implements the calculation of the animation interpolation factor. In most cases, we can use ObjectAnimator to easily implement many kinds of animation effects, then, the View using ObjectAnimator must satisfy the getter and setter methods. Without these methods, the animation using ObjectAnimator cannot be implemented. We have to consider using the ObjectAnimator parent class ValueAnimator, valueAnimator does not require the getter and setter methods in the View to implement an animation. It calculates the interpolation factor of the animation. You can customize the animation effect based on this interpolation.

 

TypeEvaluator

TypeEvaluator is an interface. By implementing the evaluate method under this interface, we can achieve custom animations for various complex effects:

 

ValueAnimator animator =ValueAnimator.ofObject(new TypeEvaluator
   
    () {@Overridepublic Number evaluate(float fraction, Number startValue,Number endValue) {// TODO Auto-generated method stubreturn null;}});
   
The above is the implemented TypeEvaluator interface. There is an unimplemented method below. This callback function provides the following three parameters:

 

Fraction: interpolation factor. value range: 0 ~ 1 startValue: the starting value of the animation. endValue: The ending value of the animation. Based on these three parameters, we can compile and calculate the animation effects we need. The styles are diverse, it's not just several animation types in ObjectAnimator. It can be seen that ValueAnimator is more flexible and more diverse than ObjectAnimator. When we customize the animation effect, we can use ValueAnimator to implement the TypeEvaluator interface to write our own animation algorithms to implement more complex animations.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.