Graphics and text detailed Android properties animation _android

Source: Internet
Author: User
Tags shallow copy

Animations in Android are divided into view animations (views Animation), Attribute animations (property Animation), and drawable animations. Starting with the Android 3.0 (API level 11), Android is starting to support property animations, and this article explains how to use attribute animations. For view animations, see the Android four view animated illustrations.

I. Overview

View animations are limited in size, as described below:

1, view animation can only be used on the view above.

2. The view animation does not really change the corresponding property values of the view, which results in a difference between the UI effect and the actual view state, and leads to a series of weird behaviors, such as touching the UI on the view that uses views animated translateanimation. You may be surprised to find that the touch event is not triggered.

Due to the above defects in view animations, attribute animations are introduced from Android 3.0. Property animations have the following characteristics:

1, the Property animation application is more extensive, not only applies to view, you can apply it to any object above, and the object does not need to have UI interface.

2. When you animate an attribute to an object, you can actually change the object's value by calling the object's Setxxx method. Therefore, when a property animation is applied to a view, the value of the property corresponding to the View object is changed.

Let's look at how the property animation works.

In fact, the working principle of the property animation is not complex, assuming that an object has an attribute x, we want to dynamically change the value through the property animation, assuming we want the value of x to be changed from 0 to 40 within 40ms, as shown in the following illustration:

As time progresses, the corresponding x values are also linearly graded, and when the animation completes, the value of X is the final value we set at 40. If the x is a linear gradient, then the change in X speed is uniform. In fact, we can change the value of x at a variable speed, which allows us to increase the value of x at the start, and then decelerate to increase the value of x, as shown in the following figure:

As shown in the above figure, the value of the former 20ms,x increases, and the 20ms,x value increases at a lower rate.

In fact, each way to change the X-value speed is called the time interpolation Timeinterpolator, the first picture used in the time interpolation is called Linearinterpolator, The time interpolation used in the second picture is called Acceleratedecelerateinterpolator. After the animation, the time interpolation will be based on the corresponding algorithm to calculate the value of a moment x, and then we can use the computed value to update the value of the X property in the object, which is the basic principle of property animation.

The main classes in the property animation are as shown in the following illustration:

The above classes are explained separately below.

Animator

Property animation The main classes are all under the Android.animation namespace, animator is the base class for property animations, an abstract class that defines many important methods, as follows:

    • Setduration (long Duration)

The Setduration method lets you set the total duration of the animation in milliseconds.

    • Start ()

The Start method lets you start the animation, which does not necessarily run immediately after the animation starts. If the animation delay time is set by calling the Setstartdelay method, the animation is run after the delay time, and if no delay time is set, the animation runs immediately after the start () method is invoked. After the start () method is invoked, the isstarted () method of the animation returns True, and the IsRunning () method of the animation returns true after the animation is actually run. This is when the animation calls Timeinterpolator to begin working on the value of the calculated property at a certain point. The thread that calls the animation's start () method must have a Looper object bound, and an error will be made if there is no binding. Of course, the UI thread (that is, the main thread) has long ago been bound by a Looper object, so we don't have to worry about it in the main thread. If we want to use attribute animation on a view, then we should make sure that we are the start () method of the animation that is invoked on the UI thread. The start () method runs and triggers the execution of the Onanimationstart method of the animation listener Animatorlistener.

    • Setstartdelay (Long Startdelay)

You can set the delay run time of an animation by calling the Setstartdelay method, such as calling Setstartdelay (1000), which means that the animation does not actually run until 1 seconds after the start () method is executed, in which case the start () is invoked Method 0.5 seconds later, the isstarted () method returns True, indicating that the animation has started, but the IsRunning () method returns False, indicating that the animation is not actually running, and that after 1 seconds after the start () method executes, isstarted () method or return the True,isrunning () method also returns True, indicating that the animation is really starting to run. By calling the Getstartdelay () method, you can return the animation delay start time that we set, the default value is 0.

    • Setinterpolator (timeinterpolator value)

We can change the time interpolation used by the animation by calling the Setinterpolator method, because the view animation also needs to use time interpolation, so we can use a series of interpolation in the Android.view.animation namespace to work with the property animation. The Getinterpolator method of animation can get the time interpolation we set.

    • Settarget (Object target)

You can update an object's property value by calling the animation's Settarget method to set the object it wants to manipulate. In fact, this method has little effect on valueanimator, because Valueanimator does not deal directly with an object. The Settarget method works great for Objectanimator because Objectanimator needs to bind to an object to be manipulated, as described in detail below.

    • Pause ()

API level 19 in Android adds the pause () method to animator, which pauses animation execution. The thread that calls the pause () method must be the same thread as the thread that called the start () method. If the animation has not yet executed the start () or the animation has ended, then invoking the pause () method has no effect and is ignored directly. When the pause () method is executed, the ispaused () method of the animation returns TRUE. The pause () method runs and triggers the execution of the Onanimationpause method of the animation listener Animatorpauselistener.

    • Resume ()

If the animation is paused by calling the pause () method, you can then allow the animation to continue from where it was last paused by calling the resume () method. The resume () method is also introduced from API level 19, and the thread that calls the resume () method must be the same thread as the thread that called the start () method. If the animation is not in a paused state (that is, ispaused () returns false), then the call to the resume () method is ignored. The resume () method runs and triggers the execution of the Onanimationresume method of the animation listener Animatorpauselistener.

    • End

The end () method executes, the animation ends, jumps directly from the current state to the final completion state, assigns the property value to the animation's termination value, and triggers the execution of the Onanimationend method of the animated listener Animatorlistener.

    • Cancel ()

When the Cancel () method is executed, the animation also ends, but unlike the call end method, it does not assign the property value to the end value of the animation. For example, an animation that changes the X property of an object from 0 to 40 within 400ms, when the Cancel () method is invoked when running to 200ms, the final value of the property X is 20, not 40, which is different from the call End () method, and if you call the ending () method at 200ms, Then the final value of attribute X is 40. When the Cancel () method is invoked, the execution of the Animatorlistener Onanimationcancel method is triggered first, and then the execution of the Onanimationend method is triggered.

    • Clone ()

Animator implements the Java.lang.Cloneable interface. The animator Clone () method copies the animation, but the method defaults to a shallow copy, which can be overridden by subclasses to implement a deep copy.

    • AddListener (Animator.animatorlistener Listener)

You can add an animated listener to animator by using the AddListener method, which receives a parameter of the Animatorlistener interface type, which has four methods: Onanimationstart, Onanimationcancel, Onanimationend, Onanimationrepeat. We've covered the first three methods above, and the Onanimationrepeat method will be recalled when the animation repeats. The Animatorlisteneradapter class in Android is an abstract class that implements the Animatorlistener interface and provides an empty implementation for all methods.

    • Addpauselistener (Animator.animatorpauselistener Listener)

You can add an animation pause-related listener to animator by using the Addpauselistener method, which receives parameters for the Animatorpauselistener interface type. There are two methods: Onanimationpause and Onanimationresume, mentioned above, no longer repeat. Animatorlisteneradapter also implements the Animatorpauselistener interface and provides an empty implementation for all methods.

Valueanimator

Valueanimator inherits from the abstract class animator. For a property animation to change the value of a property in an object gradually, you can do this in two steps: First, the animation needs to figure out what the property value should be at a given moment, and the second step is to assign the computed property value to the animated property. Valueanimator only implemented the first step, that is, Valueanimator is only responsible for the animation in the form of continuous calculation of the value of the property at different times, but we need developers to write their own code to the calculated value through the object's setxxx and other methods to update the object's property values.

There are two more important properties in the Valueanimator, one is the Timeinterpolator type and the other is the Typeevaluator type property. Timeinterpolator refers to the time interpolation, which we have described above, no longer repeat. What is Typeevaluator? Typeevaluator represents what type of value valueanimator to animate. Valueanimator provides four static methods Offloat (), Ofint (), Ofargb (), and Ofobject (), which can animate different types of values, four of which correspond to four typeevaluator, This is explained in detail below.

    • public static Valueanimator offloat (float ... values)

The Offloat method receives a series of float-type values that use Floatevaluator internally. By using this method valueanimator can animate a float value, which is shown as follows:

 Valueanimator valueanimator = Valueanimator.offloat (0f, 500f);

  Valueanimator.addupdatelistener (New Valueanimator.animatorupdatelistener () {
    @Override public
    Void Onanimationupdate (Valueanimator animation) {
      float DeltaY = (float) animation.getanimatedvalue ();
      Textview.settranslationy (DeltaY);
    }
  );

  The default duration is 300 millisecond
  valueanimator.setduration (3000);
  Valueanimator.start ();

The effect is as follows:

We specify the starting value of the animation as 0, the end value is 500, the default duration of the animation is 300 milliseconds, and we set the Setduration () method to 3000 milliseconds. The animation will change the value from 0 to 500 animation in 3 seconds. Valueanimator provides a Addupdatelistener method by which you can add a Animatorupdatelistener type listener to the method. Animatorupdatelistener has a onanimationupdate method, Valueanimator calculates the value of the property at a certain time (the default interval of 10ms). The Onanimationupdate method is recalled whenever it is calculated. In this method, we get the value of the property computed by the current animation by calling the Valueanimator Getanimatedvalue () method, and then we pass that value into the TextView settranslationy () method. This updates the position of the textview so that it moves the TextView by Valueanimator in the form of animations.

    • public static valueanimator ofint (int ... values)

The Ofint method is very similar to the Offloat method, except that the Ofint method receives the value of type int, Intevaluator is used inside the Ofint method, which can be used to refer to the code of the offloat above, no longer to repeat.

    • public static valueanimator Ofargb (int ... values)

Starting with API level 21, the Ofargb method is added to the Valueanimator, which receives columns representing the int value of the color, with argbevaluator inside it, which enables you to animate a color animation to another color, We can keep getting the color values from the intermediate animation. You may wonder, since the incoming or int value, the direct use of the Ofint method is not OK, why do you want to add a Ofargb method? In fact, you can't complete a color animation gradient with the Ofint method. We know that an int value contains four bytes, the first byte in Android represents the alpha component, the second byte represents the red component, the third byte represents the green component, the fourth byte represents the blue component, and we often use the 16 notation to represent the color, so that it seems more understandable. For example, the Int value 0xffff0000 represents the red, the 0xff00ff00 is green, and the front FF represents Alpha. The Ofargb method will split the color into four components by Argbevaluator, then animate each component separately, then regroup the four computed components into a single int value representing the color, which is how the Ofargb method works. The use method looks like this:

 The Valueanimator.ofargb () method is included in API level 21
  if (Build.VERSION.SDK_INT >=) {
    //The starting color is red
    INT StartColor = 0xffff0000;
    The Terminator color is green
    int endcolor = 0xff00ff00;
    Valueanimator valueanimator = Valueanimator.ofargb (StartColor, endcolor);
    Valueanimator.setduration (3000);
    Valueanimator.addupdatelistener (New Valueanimator.animatorupdatelistener () {
      @Override public
      Void Onanimationupdate (Valueanimator animation) {
        int color = (int) animation.getanimatedvalue ();
        Textview.setbackgroundcolor (color);
      }
    });
    Valueanimator.start ();
  }

The effect looks like this:

We will textview the colors from red to green through animation.

    • public static Valueanimator Ofobject (Typeevaluator evaluator, Object ... values)

Because the values we're animating are all sorts of things, maybe not float, int, or color values, how do we use attribute animations? To do this, Valueanimator provides a ofobject method that receives a typeevaluator type parameter, and we need to implement the Evaluate method of the interface Typeevaluator As long as we implement the Typeevaluator interface, we can handle any type of data through the Ofobject method. We mentioned earlier that the Ofargb method was introduced from API level 21, what if we wanted to use the Ofargb feature in previous versions? We can extend the typeevaluator to implement the logic of the Ofargb method through the Ofobject method, as follows:

  The starting color is red int startcolor = 0xffff0000;
  The Terminator color is green int endcolor = 0XFF00FF00; Valueanimator valueanimator = valueanimator.ofobject (new Typeevaluator () {@Override public Object evaluate (float Fraction, Object Startvalue, Object Endvalue {//the alpha, Red, Green, blue four component int startint = (in) is parsed from the original int type color value.
      Teger) Startvalue;
      int Starta = (startint >>) & 0xFF;
      int startr = (startint >>) & 0xFF;
      int STARTG = (startint >> 8) & 0xFF;

      int STARTB = startint & 0xFF;
      Resolves alpha, Red, Green, blue four component int endint = (Integer) endvalue from the color value of the terminated int type;
      int enda = (endint >>) & 0xFF;
      int Endr = (endint >>) & 0xFF;
      int ENDG = (endint >> 8) & 0xFF;

      int endb = endint & 0xFF; Calculates Alpha, Red, Green, blue four components,//FINAL synthesis of a complete int type color value return (int) (Starta + (int) (fraction * (Enda-starta)
          )) << 24) | (int) ((Startr + (int) (fraction * (ENDR-STARTR)) << 16) | (int)
          ((STARTG + (int) (fraction * (ENDG-STARTG)) << 8) | (int)
    ((STARTB + (int) (fraction * (ENDB-STARTB)));
  }, StartColor, EndColor);
  Valueanimator.setduration (3000); Valueanimator.addupdatelistener (New Valueanimator.animatorupdatelistener () {@Override public void ONANIMATIONUPDA
      Te (valueanimator animation) {int color = (int) animation.getanimatedvalue ();
    Textview.setbackgroundcolor (color);
  }
  });

 Valueanimator.start ();

The effect of the above code implementation is the same as the effect of OFARGB implementation, are textview from red to green, no longer attached, but we can in API level 11 and later versions can use the above Ofobject code, more versatile.

Objectanimator

Objectanimator inherits from Valueanimator. As we mentioned earlier, to make a property animation change the value of a property in an object gradually, you can do this in two steps: First, the animation needs to figure out what the property value should be at a given moment, and the second step is to assign the computed property value to the animated property. Valueanimator only implements the first step, meaning that Valueanimator is only responsible for constantly calculating the value of the property at different times in the form of animation. But we need developers to write their own code to update the object's property values through methods such as the object's setxxx in the Onanimationupdate method of the animated listener Animatorupdatelistener. Objectanimator is further than Valueanimator, which automatically invokes the object's Setxxx method to update the property values in the object.

Objectanimator overloads static methods such as Offloat (), Ofint (), Ofargb (), and Ofobject (), which we follow in turn.

    • Offloat (Object target, String PropertyName, float ... values)

The use method looks like this:

 float value1 = 0f;
  float value2 = 500f;
  Final Objectanimator objectanimator = objectanimator.offloat (TextView, "Translationy", value1, value2);
  Objectanimator.setduration (3000);
  Objectanimator.start ();

The effect of the above code implementation is the same as that achieved through the Valueanimator Offloat method, which is no longer attached, but it can be seen that using objectanimator code is simpler. In the constructor, we pass TextView as Target to Objectanimator, and then specify TextView the property to be changed is translationy, and finally specify the gradient range from 0 to 500. When the animation begins, Objectanimator constantly calls the TextView Settranslationy method to update its value. We demonstrate here that Objectanimator works with view, in fact Objectanimator can work with arbitrary object objects. If you want to update a property named Propery in an object, the object must have a SetProperty setter method that can be invoked by the objectanimator. At the end of the Offloat method, if only a float value is filled in, then objectanimator needs to invoke the object's GetXXX method to get the object's initial property value, and then from the initial property value to the terminating value.

    • Ofint (Object target, String propertyname, int ... values)

See how offloat is used.

    • Ofargb (Object target, String propertyname, int ... values)

Use the code as follows:

 The Objectanimator.ofargb () method is included in API level 21
  if (Build.VERSION.SDK_INT >=) {
    INT StartColor = 0xffff0000;
    int endcolor = 0xff00ff00;
    Objectanimator objectanimator = Objectanimator.ofargb (TextView, "BackgroundColor", StartColor, EndColor);
    Objectanimator.setduration (3000);
    Objectanimator.start ();
  }

The effects diagram see the corresponding picture in Valueanimator.

Ofobject (object target, String PropertyName, Typeevaluator Evaluator, object ... values)
Use the code as follows:

 int startcolor = 0xffff0000;
  int endcolor = 0XFF00FF00;
    Objectanimator objectanimator = Objectanimator.ofobject (TextView, "BackgroundColor", new Typeevaluator () {@Override 
      public object evaluate (float fraction, object Startvalue, Object endvalue) {int startint = (Integer) startvalue;
      int Starta = (startint >>) & 0xFF;
      int startr = (startint >>) & 0xFF;
      int STARTG = (startint >> 8) & 0xFF;

      int STARTB = startint & 0xFF;
      int endint = (Integer) endvalue;
      int enda = (endint >>) & 0xFF;
      int Endr = (endint >>) & 0xFF;
      int ENDG = (endint >> 8) & 0xFF;

      int endb = endint & 0xFF;
          return (int) (Starta + (int) (fraction * (Enda-starta)) << 24) | (int)
          ((STARTR + (int) (fraction * (ENDR-STARTR)) << 16) | (int)
          ((STARTG + (int) (fraction * (ENDG-STARTG)) << 8) | (int) ((STARTB + (int) (fraction * (ENDB-STARTB)));
  }, StartColor, EndColor);
  Objectanimator.setduration (3000);

 Objectanimator.start ();

Animatorset

Animatorset inherits from animator. Animatorset represents a collection of animations, which we can use to assemble multiple animations together, animatorset them serially or in parallel, creating complex animation effects.

We want TextView to rotate first, then pan, and finally scale, and we can do that by Animatorset, and the code looks like this:

The//anim1 realizes the TextView rotation animation animator anim1 = Objectanimator.offloat (TextView, "rotation", 0f, 360f);
  Anim1.setduration (2000);
  Anim2 and Anim3textview translation animation animator anim2 = Objectanimator.offloat (TextView, "Translationx", 0f, 300f);
  Anim2.setduration (3000);
  Animator anim3 = Objectanimator.offloat (TextView, "Translationy", 0f, 400f);
  Anim3.setduration (3000);
  ANIM4 realizes TextView telescopic animation animator anim4 = Objectanimator.offloat (TextView, "ScaleX", 1f, 0.5f);


  Anim4.setduration (2000);
  The first way animatorset Animatorset = new Animatorset ();
  Animatorset.playsequentially (ANIM1, anim2, ANIM4);
  Animatorset.playtogether (anim2, ANIM3);

  Animatorset.start ();
  The second way/*animatorset anim23 = new Animatorset ();
  Anim23.playtogether (anim2, ANIM3);
  Animatorset animatorset = new Animatorset ();
  Animatorset.playsequentially (ANIM1, ANIM23, ANIM4);
  Animatorset.start ();///The Third way of/*animatorset animatorset = new Animatorset ();
  Animatorset.play (ANIM1). before (ANIM2); AnimAtorset.play (ANIM2). with (ANIM3);
  Animatorset.play (ANIM4). After (ANIM2);

 Animatorset.start ();

The effect looks like this:

The animation anim1 is used to rotate the textview,anim2 used in the x-axis direction offset textview,anim3 is used to offset textview,anim4 in the y-axis direction for scaling TextView. In the above code we provide three ways to combine the four animations through Animationset, and the second and third methods are annotated.

In fact, there are many ways to achieve the above effect, here only to introduce the above three kinds of ways of thinking.

In the first approach , the animatorset.playsequentially (anim1, anim2, ANIM4) is invoked, which will anim1, ANIM2 and ANIM4 are sequentially concatenated up into the Animatorset, allowing the animation anim1 to execute first, anim1 after the execution, and then performing the animation anim2 after the anim2 is executed. by calling Animatorset.playtogether (ANIM2, anim3), anim2 and ANIM3 are guaranteed to execute simultaneously, that is, after the animation anim1 is complete, both ANIM2 and ANIM3 are run.

In the second way , we first create a Animatorset variable anim23 and then combine anim3 and anim2 into a small set of animations through Anim23.playtogether (anim2, ANIM3). Then we pass ANIM1, Anim23 and anim4 to Animatorset.playsequentially (anim1, ANIM23, anim4) so that anim1, ANIM23, and ANIM4 are executed sequentially, And the anim2 and anim3 in ANIM23 are executed simultaneously. This method also demonstrates that one animatorset can be put into another animatorset as part of the animation.

In the Third Way , we use the Animatorset play method, which returns the Animatorset.builder type, Animatorset.play (ANIM1). Before (ANIM2) Make sure the ANIM1 executes Anim2,animatorset.play (ANIM2). with (ANIM3) ensures anim2 and anim3 execute concurrently, Animatorset.play (ANIM4). After ( ANIM2) ensures that anim2 executes after execution anim4. What needs to be explained is Animatorset.play (ANIM1). Before (ANIM2) and Animatorset.play (ANIM2). After (ANIM1) is completely equivalent, the reason is in the above code is written in before, Some write after, just to let everyone know more about the API.

I hope this article will help you learn the properties of animation.

Related Article

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.