Android Property animation Property

Source: Internet
Author: User

Android Property animation Property

1. Overview

Android provides several Animation types: View Animation, Drawable Animation, and Property Animation. View Animation is quite simple, but it only supports simple scaling, translation, rotation, and transparency animations, and has certain limitations. For example, you want the View to have a color switching animation; you want to use a 3D Rotation animation; you want the View position to be the current position when the animation is stopped; none of these views can be implemented. This is why Property Animation is generated. This blog introduces the usage of Property Animation in detail. For Drawable Animation, well, slightly ~
2. Related APIs

Property Animation: the attribute of an object is changed through Animation. First, we need to understand several attributes:

Duration animation Duration. The default value is 300 ms.

Time interpolation: Time difference. At first glance, I don't know what it is, but I am talking about LinearInterpolator, AccelerateDecelerateInterpolator. You must know what it is, and define the animation change rate.

Repeat count and behavior: Repeat count and behavior. You can define the number of Repeat times.

Animation sets: an animation set. You can define an animation group to be executed together or sequentially.

Frame refresh delay: Specifies the Frame refresh delay. The default value is 10 ms, but it depends on the current state of the system.

Related Classes

ObjectAnimator animation execution class, which will be detailed later

ValueAnimator animation execution class, which will be detailed later

AnimatorSet is used to control the execution of a group of animations: linear, together, and successively executed by each animation.

AnimatorInflater: xml file for loading property Animation

The TypeEvaluator type value is mainly used to set the animation operation attribute value.

TimeInterpolator time interpolation, as described above.

In general, attribute animation is an animation execution class that sets the attributes, duration, start and end attribute values, and time difference of the animation operation object, then, the system dynamically changes the attributes of the Object Based on the set parameters.
3. ObjectAnimator Animation

Select ObjectAnimator as the firstThis is because this implementation is the simplest.One line of code is used to implement animation in seconds. The following is an example:
Layout file:

[Html] view plaincopy


        
     
   
    

It's easy, just a girl picture ~
Activity Code:

[Java] view plaincopy

package com.example.zhy_property_animation;  import android.animation.ObjectAnimator;  import android.app.Activity;  import android.os.Bundle;  import android.view.View;  public class ObjectAnimActivity extends Activity  {      @Override      protected void onCreate(Bundle savedInstanceState)      {          super.onCreate(savedInstanceState);          setContentView(R.layout.xml_for_anim);      }      public void rotateyAnimRun(View view)      {           ObjectAnimator//           .ofFloat(view, rotationX, 0.0F, 360.0F)//           .setDuration(500)//           .start();      }  }  

Effect:

Is it possible to implement simple animation with a line of code ~~

For ObjectAnimator

1. ofInt, ofFloat, and ofObject are provided. These methods are used to set the elements, attributes, start and end of the animation, and any attribute values in the middle of the animation.

When only one attribute value is set, it is considered that the value of this attribute of the object is the start (obtained by getPropName reflection), and the set value is the end point. If two values are set, the first value is the end value and the other value is the end value ~~~

During the animation update process, attributes of the setPropName update element are constantly called. All attributes updated using ObjectAnimator must have the getter (when setting an attribute value) and setter Methods ~

2. If you operate on this attribute method of the object, for example, setRotationX in the above example, if you do not call repainting of view internally, You need to manually call it as follows.

[Java] view plaincopy

anim.addUpdateListener(new AnimatorUpdateListener()          {              @Override              public void onAnimationUpdate(ValueAnimator animation)              {  //              view.postInvalidate();  //              view.invalidate();              }          });  

3. After reading the example above, because only one attribute is set for the operation, if I want an animation to make the View zoom out and fade out, scaleY, alpha), only use ObjectAnimator. What should I do?

The idea is not very good. It may be said that the use of AnimatorSet is a bunch of animation plug-ins for execution, but I have to use an ObjectAnimator instance for implementation ~ See the code below:

[Java] view plaincopy

public void rotateyAnimRun(final View view)  {      ObjectAnimator anim = ObjectAnimator//              .ofFloat(view, zhy, 1.0F,  0.0F)//              .setDuration(500);//      anim.start();      anim.addUpdateListener(new AnimatorUpdateListener()      {          @Override          public void onAnimationUpdate(ValueAnimator animation)          {              float cVal = (Float) animation.getAnimatedValue();              view.setAlpha(cVal);              view.setScaleX(cVal);              view.setScaleY(cVal);          }      });  }  

Write the character string that sets the attribute to an attribute that is not available to the object ~~ We only need the value calculated by time interpolation and duration, and we manually call it ~

Effect:

In this example, I want to explain that sometimes I don't want to be restricted by the API, and some functions provided by the API can also achieve interesting results ~~~

For example, if you want to achieve the parabolic effect, 100px/s in the horizontal direction, and 200px/s * s in the vertical direction, how can this be achieved ~~ You can try it with ObjectAnimator ~

4. There is actually a simpler way to change multiple effects of an animation: Using propertyValuesHolder

[Java] view plaincopy

public void propertyValuesHolder(View view)      {          PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat(alpha, 1f,                  0f, 1f);          PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat(scaleX, 1f,                  0, 1f);          PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat(scaleY, 1f,                  0, 1f);          ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY,pvhZ).setDuration(1000).start();      }  

4. ValueAnimator Animation

Similar to ObjectAnimator, you can simply look at the animation code for vertical movement of a view:

[Java] view plaincopy

public void verticalRun(View view)      {          ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight                  - mBlueBall.getHeight());          animator.setTarget(mBlueBall);          animator.setDuration(1000).start();      }  

Does it make you feel like it is? It's different from ValueAnimator ~ However, you can see that no operation attribute is set ~~ That is to say, the above Code has no effect and no attribute is specified ~

This is the difference between ValueAnimator and ValueAnimator: ValueAnimator does not perform operations on attributes. What are the advantages of ValueAnimator? Don't I have to set it manually?

Benefit: the attributes of objects that do not need to be operated must have the getter and setter methods. You can operate any attribute based on the calculated value of the current animation, remember the one in the above example [I want an animation to make the View zoom out and fade out (three attributes: scaleX, scaleY, and alpha? This is actually the usage ~

Instance:

Layout file:

[Html] view plaincopy


        
         
    
     
    
   
            

There is a small ball in the upper left corner and two buttons at the bottom ~ Let's first look at a free-body code:

[Java] view plaincopy

/*** @ ** @ Param view */public void verticalRun (View view) {ValueAnimator animator = ValueAnimator. ofFloat (0, mScreenHeight-mBlueBall. getHeight (); animator. setTarget (mBlueBall); animator. setDuration (1000 ). start (); // animator. setInterpolator (value) animator. addUpdateListener (new AnimatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {mBlueBall. setTranslationY (Float) animation. getAnimatedValue ());}});}

Unlike ObjectAnimator, we set the update of element attributes ~ Although several lines of code are added, it seems to improve flexibility ~

Next, let's take another example. If I want a small ball to perform parabolic motion [to achieve the parabolic effect, 100px/s in the horizontal direction, and 200px/s in the vertical direction], let's analyze it, it seems to be related only to time, but the horizontal and vertical moving rates vary according to time changes. How can we achieve this? At this point, it is time to rewrite TypeValue, because we need to return two values to the object, the current position of x, and the current position of y, when time changes:

Code:

[Java] view plaincopy

/*** Parabolic * @ param view */public void paowuxian (View view) {ValueAnimator valueAnimator = new ValueAnimator (); valueAnimator. setDuration (3000); valueAnimator. setObjectValues (new PointF (0, 0); valueAnimator. setInterpolator (new LinearInterpolator (); valueAnimator. setEvaluator (new TypeEvaluator
  
   
() {// Fraction = t/duration @ Override public PointF evaluate (float fraction, PointF startValue, PointF endValue) {Log. e (TAG, fraction * 3 +); // 200px/s in the x direction, 0.5*10 * t PointF point = new PointF (); point. x = 200 * fraction * 3; point. y = 0.5f * 200 * (fraction * 3) * (fraction * 3); return point ;}}); valueAnimator. start (); valueAnimator. addUpdateListener (new AnimatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {PointF point = (PointF) animation. getAnimatedValue (); mBlueBall. setX (point. x); mBlueBall. setY (point. y );}});}
  

We can see that, because ofInt, ofFloat, and so on cannot be used, we customize a TypeValue and return a PointF object each time based on the current time. (the difference between PointF and Point is x, the unit of y is float and int. RectF and Rect are also) PointF contains the current position of x and y ~ Then we get it in the listener and dynamically set the attributes:

:

There is a feeling that two iron balls are landing at the same time ~~ Yes. I should have two balls ~~ Ps: if the physical formula is wrong, you will not see it.

Custom generic input by TypeEvaluator can design a Bean as needed.

Now, we have explained the differences between ValueAnimator and ObjectAnimator for implementing animation. How to Use Some APIs to update attributes and customize TypeEvaluator to meet our needs; but we didn't talk about how to design interpolation. In fact, I think the default implementation class of this interpolation is enough ~~ Very few, will design a super abnormal ~ Hmm ~ So: omitted.
5. Listen to animation events

For animations, they are generally secondary effects. For example, if I want to delete an element, I may want to fade out the effect, but I still want to delete it, not because you have no transparency, it still occupies the position, so we need to know how the animation ends.

So we can add an animation listener:

[Java] view plaincopy

public void fadeOut(View view)      {          ObjectAnimator anim = ObjectAnimator.ofFloat(mBlueBall, alpha, 0.5f);          anim.addListener(new AnimatorListener()          {              @Override              public void onAnimationStart(Animator animation)              {                  Log.e(TAG, onAnimationStart);              }              @Override              public void onAnimationRepeat(Animator animation)              {                  // TODO Auto-generated method stub                  Log.e(TAG, onAnimationRepeat);              }              @Override              public void onAnimationEnd(Animator animation)              {                  Log.e(TAG, onAnimationEnd);                  ViewGroup parent = (ViewGroup) mBlueBall.getParent();                  if (parent != null)                      parent.removeView(mBlueBall);              }              @Override              public void onAnimationCancel(Animator animation)              {                  // TODO Auto-generated method stub                  Log.e(TAG, onAnimationCancel);              }          });          anim.start();      }  

In this way, you can listen to events such as the start, end, cancellation, and repetition of an animation ~ However, sometimes I feel that I only need to know the end, so long code I cannot receive, then you can use the AnimatorListenerAdapter

[Java] view plaincopy

anim.addListener(new AnimatorListenerAdapter()  {      @Override      public void onAnimationEnd(Animator animation)      {          Log.e(TAG, onAnimationEnd);          ViewGroup parent = (ViewGroup) mBlueBall.getParent();          if (parent != null)              parent.removeView(mBlueBall);      }  });  

AnimatorListenerAdapter inherits the AnimatorListener interface, and then empty implements all the methods ~

:

The animator and cancel () and end () Methods: The cancel animation stops immediately and stops at the current position. The end animation goes directly to the final state.

6. Use of AnimatorSet

Instance:

Layout file:

[Html] view plaincopy


        
         
    
     
    
   
            

Continue playing the ball ~

Code:

[Java] view plaincopy

Package com. example. zhy_property_animation; import android. animation. animatorSet; import android. animation. objectAnimator; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. animation. linearInterpolator; import android. widget. imageView; public class AnimatorSetActivity extends Activity {private ImageView mBlueBall; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. anim_set); mBlueBall = (ImageView) findViewById (R. id. id_ball);} public void togetherRun (View view) {ObjectAnimator anim1 = ObjectAnimator. ofFloat (mBlueBall, scaleX, 1.0f, 2f); ObjectAnimator anim2 = ObjectAnimator. ofFloat (mBlueBall, scaleY, 1.0f, 2f); AnimatorSet animSet = new AnimatorSet (); animSet. setDuration (2000); animSet. setInterpolator (new LinearInterpolator (); // The animSet is executed for both animations. playTogether (anim1, anim2); animSet. start ();} public void playWithAfter (View view) {float cx = mBlueBall. getX (); ObjectAnimator anim1 = ObjectAnimator. ofFloat (mBlueBall, scaleX, 1.0f, 2f); ObjectAnimator anim2 = ObjectAnimator. ofFloat (mBlueBall, scaleY, 1.0f, 2f); ObjectAnimator anim3 = ObjectAnimator. ofFloat (mBlueBall, x, cx, 0f); ObjectAnimator anim4 = ObjectAnimator. ofFloat (mBlueBall, x, cx);/*** anim1, anim2, anim3 simultaneously execute * anim4 and then execute */AnimatorSet animSet = new AnimatorSet (); animSet. play (anim1 ). with (anim2); animSet. play (anim2 ). with (anim3); animSet. play (anim4 ). after (anim3); animSet. setDuration (1000); animSet. start ();}}

Two effects are written:

First, use playTogether to execute the animation at the same time, and playSequentially to execute the animation in sequence ~~

Second, if we have a bunch of animations, how can we use code to control the sequence, such as 1, 2, 3, 2, 4, and so on ~ It's Effect 2.

Note: animSet. play (). with (); also supports chain programming, but do not think crazy, such as animSet. play (anim1 ). with (anim2 ). before (anim3 ). before (anim5); this is not the case. The system won't decide the sequence based on the long string you wrote. So please write several more lines according to the example above:

:

 

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.