Android Learning Properties Animation <property animation>

Source: Internet
Author: User

The property animation system is a fairly robust framework that can animate almost any object. You can define an animation to periodically change the property value of any object, whether or not the object is displayed on the screen. Property animations Modify the value of the attribute (the field value in the object) at a certain time interval. To animate, you must specify the corresponding properties of the object (such as the screen position of the object), as well as the duration of the animation and the animation interval.

The property animation system allows you to set the following animation elements:
1. Duration: Specifies the duration of the animation to be displayed. The default duration is 300 milliseconds.
2. Interpolation factor: Specifies how the property value changes, expressed as a function of how long the animation has been displayed.
3. Repeat number and mode: Specifies whether the animation loops and the number of repetitions. You can also specify whether the animation plays backwards. Can be set to forward playback 4. Reverse back again, so that it repeats until the set number of repetitions is reached.
5. Animation collection: You can divide the animation into logical groups for simultaneous playback, sequential playback, or a period of time before playback.
6. Frame Refresh interval: Specifies how often the animation frames are refreshed. The default is to refresh every ten MS, but the actual amount of refresh the application can perform depends on how busy the system is, and how much the system supports the timer.

I. How the property animation works
First, let's review how the animation works with a simple example. Figure 1 shows the change in the X property of an object, which is the horizontal position on the screen. The duration of the animation is set to four MS, and the distance traveled is 40 pixels. Every ten MS, this is the default frame refresh rate, which moves the object 10 pixels across the landscape. After the MS expires, the animation stops, and the object moves 40 pixels across the position. The following is an example of linear interpolation, which means that the object moves at a fixed speed.

Figure 1. Examples of linear animations
You can also set the animation to a nonlinear interpolation method. Figure 2 shows that an object moves at the beginning of acceleration and slows down at the end. This object still moves 40 pixels in a range of four MS, but the speed is nonlinear. At the beginning, this animation accelerates to the middle position and then slows down to the end. As shown in 2, the start and end phases move less than the middle.

Figure 2. Examples of nonlinear animations
Let's take a closer look at the computational process of the key parts of the property animation system in the above animation. Figure 3 shows how the main classes work together.

Figure 3. The calculation process of animation
1. The Valueanimator object records some values of the animation itself, such as how long it has been shown, and the current value of the animation's corresponding property.
2. Valueanimator encapsulates a timeinterpolator that defines how the animation changes, and typeevaluator that defines how the property is computed. For example, the timeinterpolator in Figure 2 should use Acceleratedecelerateinterpolator, Typeevaluator should use Intevaluator. To start an animation, create a valueanimator and specify the initial and end values of the properties to animate. Call Start () to start the animation. Throughout the animation, Valueanimator calculates a time scale factor (elapsed fraction) that is between 0 and 1 based on the total animation time and the time that has been done. The time scale factor represents the percentage of time that the animation has completed, and 0 indicates that 0%,1 represents 100%. For example, in Figure 1, the time scale factor for t = Ten MS should be 0.25, because the total time t = Ms.
3, valueanimator after calculating the time scale factor, the set Timeinterpolator is called to calculate an interpolation factor (interpolated fraction). An interpolation factor is an image display state factor that is converted from a time scale factor. For example, in Figure 2, T = Ten MS, because the animation has a smaller acceleration, the interpolation factor is about 0.15, which is less than the time scale factor of 0.25. In Figure 1, the interpolation factor remains constant and is consistent with the time scale factor. After calculating the interpolation factor, Valueanimator calls the appropriate typeevaluator to calculate the attribute values that need to be animated based on the interpolation factor, the initial value, and the end value. For example, in Figure 2, the interpolation factor at t = Ten MS is 0.15, so the attribute value at this point should be 0.15 X (40-0), or 6.

API Overview
You can find the API for most property animation systems in Android.animation. Because the view animation system has defined many interpolator in android.view.animation, you can use them directly in the property animation system. The following table describes the main contents of the property animation system.
The Animator class provides only the underlying construction method used to create the animation. It only provides the most basic functionality, you must extend these features to complete support for animations, so you should not normally use this class directly. The following sub-classes extend the Animator:
Table 1. Animator


Evaluator is used to tell the property animation system how to calculate a given attribute value. Based on the timing data given by the Animator class, the animation initial value and the end value, it calculates the value of the property that needs to be animated. The property animation system provides the following evaluator:
Table 2. Evaluator


Time Interpolator defines how the animation is displayed, which is a function of time. For example, you can specify the linear playback animation, which is the full speed playback. Alternatively, you can specify non-linear playback, such as accelerating at the beginning and slowing down near the end. Table 3 lists the interpolator included in the android.view.animation. If the existing interpolator does not meet the requirements, you can implement the Timeinterpolator interface and create your own interpolator. A method for writing custom interpolator.
Table 3. Interpolator


Second, using Valueanimator to achieve animation
By specifying a set of int, float, and color values, the Valueanimator class allows you to modify certain types of values during animation. You can obtain a Valueanimator instance by calling its factory method (Factory methods): Ofint (), Offloat (), Ofobject (). Like what:
Valueanimator animation = Valueanimator.offloat (0f, 1f); Animation.setduration (+); Animation.start ();
In this code, Valueanimator first sets the animation value to 0-1, continuous MS, and executes the start () method.
You can also specify the animation value of a custom type in the following format:
Valueanimator animation = Valueanimator.ofobject (new Mytypeevaluator (), Startpropertyvalue, Endpropertyvalue); Animation.setduration (+); Animation.start ();

In this code, Valueanimator first calculates the animation value between Startpropertyvalue to Endpropertyvalue, applies mytypeevaluator, lasts for MS, and executes start ().


In fact, this code does not animate an object because Valueanimator has no direct control over the object or its property values. The most likely thing you'll want to do is modify the animated object with the computed attribute value. You can do this by defining the listener in Valueanimator. Listeners can implement event handling during animation, such as the refresh of frames. In the implementation code of the listener, you can call Getanimatedvalue () to get the computed property values for this screen refresh.

Third, using Objectanimator to achieve animation
Objectanimator is a subclass of Valueanimator, which is a combination of the timing engine and the property values of the computed target object valueanimator. Because the property values will be updated automatically, you no longer need to implement Valueanimator.animatorupdatelistener, so it's easier to animate any object.
The Objectanimator example is similar to Valueanimator, except that you also need to specify an additional object and property name (string format) before the animation interval value:
Objectanimator anim = objectanimator.offloat (foo, "Alpha", 0f, 1f); Anim.setduration (+); Anim.start ();
To ensure that Objectanimator is able to update the property values correctly, you must do the following:
1. The animated display must have a setter method (named in Camel spelling), formatted like set<propertyname> (). Because Objectanimator automatically updates the property values during the animation, it must be able to access the property with this setter method. For example, if the attribute name is foo, you need to have a Setfoo () method. If this setter method does not exist, you have the following three options:
1> If you have permission, add this setter method directly to the class.
2> adds this setter method with the wrapper class you have permission to modify, and lets the wrapper class receive the property value and pass it to the original object.
3> swap with Valueanimator.
2, if you call a factory method of Objectanimator, you only for the values ... parameter specifies a value that will be considered as the end value of the animation property. In this case, the animated display must have a getter method that gets the starting value of the animation. This getter method must be named in the Format get<propertyname> (). For example, if the property name is Foo, you need to have a Getfoo () method.
3. The getter method of the animated property (if necessary) and the setter method must have the same type of data as the starting and ending values set in Objectanimator. For example, if you set up the following objectanimator, then you must have Targetobject.setpropname (float) and targetobject.getpropname (float):
Objectanimator.offloat (TargetObject, "propname", 1f)
4. Depending on the animation display objects and attributes, perhaps you need to call the View's invalidate () method to force repainting of the screen with the new property values. You should perform a refresh operation in the Onanimationupdate () callback method. For example, to animate the color properties of a Drawable object, you only have to redraw to show changes on the screen. All property setter methods in view, such as Setalpha () and Settranslationx (), will disable view in a timely manner, so you do not need to disable view when calling these methods with new property values.

Iv. arranging multiple animations with Animatorset
Many times, you need to play another animation at the beginning and end of an animation. The Android system allows you to combine multiple animations into a single animatorset, so you can set them to play at the same time, play sequentially, or delay them for a while. You can also nest multiple Animatorset objects.
As the following example, the Animator object is played with the following rules:
1, play Bounceanim.
2. Play SquashAnim1, squashAnim2, STRETCHANIM1 and stretchAnim2 at the same time.
3, play Bouncebackanim.
4, play Fadeanim.
Animatorset bouncer = new Animatorset (); Bouncer.play (Bounceanim). before (SQUASHANIM1); Bouncer.play (SQUASHANIM1). With (SQUASHANIM2); Bouncer.play (SQUASHANIM1), with (STRETCHANIM1), Bouncer.play (SQUASHANIM1). with (STRETCHANIM2); Bouncer.play (Bouncebackanim). After (STRETCHANIM2); Valueanimator Fadeanim = objectanimator.offloat (Newball, "Alpha", 1f, 0f); fadeanim.setduration (250); Animatorset animatorset = new Animatorset (); Animatorset.play (Bouncer). before (Fadeanim); Animatorset.start ();

Five, the animation listener
During playback, you can use the following listeners to listen for important animated events.
Animator.animatorlistener
Onanimationstart ()--called when the animation starts.
Onanimationend ()--called at the end of the animation.
Onanimationrepeat ()--called when the animation loop plays.
Onanimationcancel ()--called when the animation is canceled. The canceled animation will still call Onanimationend () regardless of the way it is terminated.
Valueanimator.animatorupdatelistener
Onanimationupdate ()--called when the animation plays every frame. During an animation, you can listen for this event to get and use Valueanimator computed property values. Using the Valueanimator object of the incoming event, call its Getanimatedvalue () method to get the current property value. If you use Valueanimator, you must implement this listener.
Depending on the animated object and its properties, you may need to call the View's invalidate () method to force the screen area to be redrawn with the new property value. For example, to animate the color properties of a Drawable object, only repainting can show changes on the screen. All property setter methods in view, such as Setalpha () and Settranslationx (), will disable view in a timely manner, so you do not need to disable view when calling these methods with new property values.
If you don't want to implement all the methods in Animator.animatorlistener, you can extend the Animatorlisteneradapter class instead of the listener. The Animatorlisteneradapter class implements an empty method body for all methods, and you can choose and overwrite it yourself.
For example, the following example creates a animatorlisteneradapter with only the Onanimationend () callback method
Valueanimatoranimator Fadeanim = objectanimator.offloat (Newball, "Alpha", 1f, 0f); fadeanim.setduration (250); Fadeanim.addlistener (New Animatorlisteneradapter () {public void Onanimationend (Animator animation) {    Balls.remove (((objectanimator) animation). Gettarget ());}

vi. Animation of layout in ViewGroup
As simple as the View animation, the property animation system provides support for animating the ViewGroup object.
You can animate the Layout in ViewGroup using the Layouttransition class. The appearance and disappearance of a view can be achieved by adding or removing the view from the ViewGroup, or by invoking the view's Setvisibility () method with VISIBLE, INVISIBLE, GONE. When you add or remove a view, other view in the ViewGroup can also be animated to the new location display. You can call the Setanimator () method of the Layouttransition object to define the following animation methods, which are Animator objects and the following Layouttransition constants:
The appearing--element needs to be animated when it appears in the container.
change_appearing--due to the appearance of a new element in the container, changes to other elements need to be animated.
The disappearing--element needs to be animated when it disappears in the container.
change_disappearing--due to the disappearance of an element in the container, changes to other elements need to be animated.
You can define your own animations for these four events in order to customize the appearance of the layout changes, or simply to notify the animation system to use the default animation mode.
Sample code:
1, you need to set the Android:animatelayoutchanges property of ViewGroup to True. Like what:
<linearlayout    android:orientation= "vertical"    android:layout_width= "wrap_content"    android:layout _height= "Match_parent"    android:id= "@+id/verticalcontainer"    android:animatelayoutchanges= "true"/>
Setting this property to True will automatically animate the view join and move out of the ViewGroup, and the other view in the ViewGroup will be animated in the same way.

2. Set layout change animation for ViewGroup
Layouttransition mtransition = new Layouttransition (); Mtransition.setanimator (                  layouttransition.appearing,                  Objectanimator.offloat (This, "ScaleX", 0, 1)); Mgridlayout.setlayouttransition (mtransition);  

PS: More detailed cases can refer to a blog from the Great God of Hon Yang:

http://blog.csdn.net/lmj623565791/article/details/38092093


Vii. Use of Typeevaluator
If the Android system does not recognize the type of attribute value that needs to be animated, you can create your own evaluator and implement Typeevaluator. Types recognized by the Android system include int, float, and color, supported by Intevaluator, Floatevaluator, and Argbevaluator, respectively.
As long as a method is implemented in the Typeevaluator interface, it is evaluate (). This method returns a property value for the current animation moment. The Floatevaluator class demonstrates this process:
public class Floatevaluator implements Typeevaluator {public    Object evaluate (float fraction, Object startvalue, Obje CT endvalue) {        float startfloat = ((number) startvalue). Floatvalue ();        return startfloat + fraction * ((number) endvalue). Floatvalue ()-startfloat);}    }
Attention:
When Valueanimator (or objectanimator) runs, it calculates the current scale of the animation process (between 0 and 1) that is currently displayed, and then computes the interpolation factor based on the interpolator used. The fraction parameter that Typeevaluator receives is itself the interpolation factor, so you don't have to use interpolator when you calculate the value of an animated property.

viii. use of Interpolator
The Interpolator (interpolator) defines the rules for changing the value of a property during animation, which is a function of time. For example, you can set the animation process to a linear change, which means that it is always changing at a constant speed. Alternatively, you can set the animation to be non-linear, such as accelerating or slowing down at the beginning or end.
The interpolator in the animation system receives a time scale factor from the Animator, which represents the time the animation has been displayed. Interpolator modifies this factor based on the type of animation. The Android system provides a common set of interpolator in the Android.view.animation package. If these are not enough, you can implement the Timeinterpolator interface to create your own interpolator.
As an example, the default Acceleratedecelerateinterpolator and Linearinterpolator interpolator will calculate the interpolation factor in the following ways:
Acceleratedecelerateinterpolator
public float getinterpolation (float input) {    return (float) (Math.Cos ((input + 1) * Math.PI)/2.0f) + 0.5f;}
Linearinterpolator
public float getinterpolation (float input) {    return input;}

Nine, set key frame
The Keyframe object contains a key-value pair for a time/attribute value that defines the animation state for a moment. Each keyframe can also have its own interpolator, which controls the animation behavior between the previous keyframe and the key frame.
To instantiate a Keyframe object, you must use one of its factory methods Ofint (), Offloat (), Ofobject (), or obtain the appropriate type of keyframe. Then, call the Factory method Ofkeyframe () to get a Propertyvaluesholder object. Once you have this object, you can get a animator of it and the object you want to animate as a parameter. The following code snippet illustrates this process:
Keyframe kf0 = Keyframe.offloat (0f, 0f); Keyframe Kf1 = Keyframe.offloat (. 5f, 360f); Keyframe Kf2 = keyframe.offloat (1f, 0f); Propertyvaluesholder pvhrotation = propertyvaluesholder.ofkeyframe ("Rotation", kf0, Kf1, KF2); objectanimator Rotationanim = Objectanimator.ofpropertyvaluesholder (target, pvhrotation) rotationanim.setduration (5000ms); Rotationanim.start ();

10. Animation Display View
The property animation system allows the view object to be animated in a series of animations, with more advantages than the View animation system.The View animation system changes the View object'show to Drawto achieve animation effects. Because view itself does not give attributes for control, this is handled by the view's container. Although this allows the view to animate, the View object itself does not change。 So this happens: Although the display position on the screen has been moved, the object still remains in its original position. In order to eliminate this disadvantage, in Android 3.0 added some new properties and the corresponding getter, setter method.
The 1> property animation system can be animated on-screen by modifying the actual value of the View object's properties. Also, when the value of the property changes, the views automatically call the Invalidate () method to refresh the screen. The new properties in the View class that are easy to implement property animations include:
2> Translationx and Translationy: These two properties control the change in the screen position coordinate of the View, with the upper-left corner of the layout container as the origin of the coordinates.
3> rotation, RotationX, and RotationY: These three properties control the 2D rotation angle (the Rotation property) and the 3D rotation angle around a pivot point.
4> ScaleX, ScaleY: These two properties control the 2D zoom ratio of the View around a pivot point.
5> Pivotx and Pivoty: These two properties control the position of the pivot point, which is centered on the rotation and scaling described above. The default pivot point is the center point of the View object.
Note: 1. Set the rotation/scaling pivot point coordinates of a view by calling Mview.setpivotx () and Mview.setpivoty ().
2. At this point the origin coordinate (0,0) is the upper-left corner of the rotation/scale view, instead of the X and Y coordinate origin in the upper left corner of the phone screen.
6> x and Y: This refers to the final position of the view within the container, equal to the value of the upper-left corner of the view with respect to the container's coordinates plus TRANSLATIONX and translationy.
7> Alpha: Represents the alpha transparency of the View. The default value is 1 (opaque), and 0 indicates full transparency (invisible).
To animate an attribute of a View object, such as a color or rotation, all you have to do is create a property animator and set the corresponding view property. Like what:
Objectanimator.offloat (MyView, "rotation", 0f, 360f);

11, using Viewpropertyanimator to achieve animation
Using a basic Animator object, Viewpropertyanimator provides a quick way to animate multiple properties of a View simultaneously. This is similar to a objectanimator because the actual property values of the View are also modified, but it is more efficient to animate multiple properties at once. In addition, code that uses Viewpropertyanimator is much simpler and more readable. The following code snippet shows simultaneous changes to the X and Y properties of view using multiple Objectanimator objects, a single Objectanimator object, and a Viewpropertyanimator object.
Multiple Objectanimator objects
Objectanimator animx = objectanimator.offloat (MyView, "X", 50f); Objectanimator animy = Objectanimator.offloat (MyView, " Y ", 100f); Animatorset animsetxy = new Animatorset () Animsetxy.playtogether (ANIMX, Animy); Animsetxy.start ();
Single Objectanimator
Propertyvaluesholder PVHX = propertyvaluesholder.offloat ("x", 50f); Propertyvaluesholder pvhy = propertyvaluesholder.offloat ("y", 100f); Objectanimator.ofpropertyvaluesholder (MyView, PVHX, Pvyy). Start (); Viewpropertyanimator
Viewpropertyanimator
Myview.animate (). x (50f). Y (100f);

12. Declaring animations in XML
The property animation system allows you to declare property animations in XML without having to write code to implement them. With XML definitions, you can easily reuse animation resources in multiple activity, and make it easier to organize animation sequences.
To differentiate between using the new Property animation API and an animation file that uses the previous View animation framework, you should save the property animation XML file to the res/animator/directory (not res) since Android 3.1. /anim/directory). The directory name animator can be modified, but if you want to use the Eclipse ADT (ADT 11.0.0+) plugin as the layout Editing tool, you can't move. Because ADT will only search for animation resources under the res/animator/directory.
The following is a list of the property animation classes available for XML markup declarations:
Valueanimator-<animator>
Objectanimator-<objectAnimator>

Animatorset-<set>


The following example plays two sets of animations in sequence, with the animation of two objects embedded in the first set of animations:
<set android:ordering= "sequentially" >    <set>        <objectanimator            android:propertyname= "x"            android:duration= "android:valueto="            android:valuetype= "Inttype"/>        < Objectanimator            android:propertyname= "y"            android:duration= "x"            android:valueto= "            android: Valuetype= "Inttype"/>    </set>    <objectanimator        android:propertyname= "Alpha"        android:duration= "1f"        android:valueto= "/></set>"
In order to play this animation, you must place the XML resource in Animatorset with code, then set all the target objects of the animation, and then start the animation. Using Settarget () makes it easy to set a target object for all child elements under Animatorset. The following code shows this setup method:
Animatorset set = (Animatorset) animatorinflater.loadanimator (mycontext,    r.anim.property_animator); Set.settarget (MyObject); Set.start ();


Note: This article is reproduced in: http://blog.sina.com.cn/s/blog_48d4913001011a1u.html [the Long-stay prawn: API Translation Series]

English Original: http://developer.android.com/guide/topics/graphics/prop-animation.html




Android Learning Properties Animation <property animation>

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.