Android Animation Learning Note-android Animation

Source: Internet
Author: User

Before 3.0, Android supported two animation modes, tween Animation,frame animation, and introduced a new animation system in android3.0: Property animation, These three animation modes are called Property Animation,view animation,drawable animation in the SDK. You can use the property Animation in a system prior to 3.0 through the Nineoldandroids project

1. View Animation (Tween Animation)

View Animation (Tween Animation): Motion tween, gives two keyframes, with some algorithms to ramp a given attribute value between two keyframes in a given time.

View animation can only be applied to view objects, and only a subset of properties are supported, such as scaling rotation and not supporting background color changes.

And for view animation, it just changes the location of the view object's drawing without changing the view object itself, for example, you have a button, coordinate (100,100), width:200,height : 50, and you have an animation to make it into width:100,height:100, you will find that the area of the trigger button click in the animation process is still (100,100)-(300,150).

The view animation is a series of view shape transformations, such as size scaling, transparency change, position change, the definition of animation can be defined in either code or XML, of course, it is recommended to use XML definition.

You can animate a view at the same time, such as from transparent to opaque fade-in effects, from small to large, these animations can be done at the same time, or you can start another after one completes.

XML-defined animations are placed inside the/res/anim/folder, and the root element of the XML file can be <alpha>,<scale>,<translate>,<rotate> Interpolator element or <set> (represents the set of several animations above, set can be nested). By default, all animations are performed simultaneously, and the start offset (start time) of each animation can be set by the Startoffset property to achieve the effect of animation order playback.

You can change the way the animation fades by setting the Interpolator property, such as Accelerateinterpolator, start slowly, and then gradually accelerate. The default is Acceleratedecelerateinterpolator.

After you have defined the animated XML file, you can apply the animation to the specified view by code similar to the following.

ImageView spaceshipimage = (ImageView) Findviewbyid (r.id.spaceshipimage);
Animation hyperspacejumpanimation=animationutils.loadanimation (this, r.anim.hyperspace_jump);
Spaceshipimage.startanimation (hyperspacejumpanimation);
2. Drawable Animation (Frame Animation)

Drawable Animation (frame Animation): Frame animation, like a GIF picture, simulates the effect of animation by displaying a series of drawable in turn. The definition in XML is as follows:

<animation-list xmlns:android= "http://schemas.android.com/apk/res/android"    android:oneshot= "true" >    <item android:drawable= "@drawable/rocket_thrust1" android:duration= "$"/> <item    android: drawable= "@drawable/rocket_thrust2" android:duration= "/>    <item android:drawable=" @drawable/rocket_ Thrust3 "android:duration="/></animation-list>

You must use <animation-list> as the root element, <item> to represent the picture to rotate, and the duration property to indicate when the items are displayed. The XML file should be placed in the/res/drawable/directory. Example:

protected void OnCreate (Bundle savedinstancestate) {
TODO auto-generated Method Stub
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
ImageView = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);
Imageview.setbackgroundresource (R.drawable.drawable_anim);
Anim = (animationdrawable) imageview.getbackground ();
}

public boolean ontouchevent (Motionevent event) {
if (event.getaction () = = Motionevent.action_down) {
Anim.stop ();
Anim.start ();
return true;
}
Return Super.ontouchevent (event);
}

I encountered two problems in the experiment:

    1. To call ImageView's Setbackgroundresource method in code, set its Src property directly in the XML layout file when the animation is triggered by FC.
    2. Stop () before the animation start (), or it will stop at the last frame after the first animation, so the animation will only fire once.
    3. The last point is mentioned in the SDK, do not call start in OnCreate, because animationdrawable is not fully associated with the window, if you want the interface to start animation, you can be in the onwindowfoucschanged () Call Start () in the
3. Property Animation

Property animation, this is introduced in Android 3.0, the previous learning of WPF inside the animation mechanism seems to be this, it changes the actual properties of the object, in view Animation (Tween Animation), it changes the view of the drawing effect, The real view property remains the same, for example, regardless of how you scale the button in the conversation, the active click area of the button or the area where the animation is not applied, and its position and size are the same. In property animation, the actual properties of the object are changed, such as the zoom of the button, and the position and size property values of the button are changed. and property animation can be applied not only to view, but also to any object. Property animation just represents a change in a value over time, and it's up to you to decide what to do when it changes.

In property animation, you can apply the following properties to the animation:

    • Duration: Duration of animation
    • Timeinterpolation: How property values are calculated, such as fast and slow
    • Typeevaluator: Calculates the current time property value based on the attribute's start, end value, and timeinterpolation calculated factor
    • Repeat Count and Behavoir: repetitions and modes, such as playing 3 times, 5 times, infinite loops, can be repeated this animation, or play back again
    • Animation sets: An animated collection that allows you to apply several animations to an object at the same time, which can be played simultaneously or at different starting offsets for different animation settings
    • Frame refreash delay: How much time to refresh, that is, how many times the property value is computed once, the default is 10ms, the final refresh time is also affected by the system process scheduling and hardware
How the 3.1 property animation works

For animations, the x-coordinate of this object is moved from 0 to pixel in 40ms. By default 10ms refreshes, the object moves 4 times, each time it moves the 40/4=10pixel.

It is also possible to change the method of changing the property value, that is, to set the different interpolation, and then gradually increase the velocity of the movement and decrease it gradually.

Shows the key objects related to the above animations

Valueanimator represents an animation that contains properties such as the start value of the animation, the ending value, the duration, and so on.

Valueanimator encapsulates a timeinterpolator,timeinterpolator that defines the interpolation method between the start and end values of a property value.

The Valueanimator also encapsulates a typeanimator that calculates the value of the attribute based on the value of the start, end value, and timeiniterpolator calculations.

Valueanimator calculates a time factor (0~1) based on the ratio of the animation's time to the total animation time (duration), and then calculates another factor based on the timeinterpolator. Finally, Typeanimator calculates the attribute value by this factor, as in the example above 10ms:

The time factor, the elapsed time percentage, is calculated first: t=10ms/40ms=0.25

Interpolation factor after interpolation (Inteplator): Approximately 0.15, the above example uses Acceleratedecelerateinterpolator, the formula is (input is the time factor):

(Math.Cos (input + 1) * Math.PI)/2.0f) + 0.5f;  

Finally, the attribute value at 10MS is calculated based on Typeevaluator: 0.15* (40-0) =6pixel. In the above example, Typeevaluator is Floatevaluator, and the method is calculated as:

public float evaluate (float fraction, number startvalue, number Endvalue) {    float startfloat = Startvalue.floatvalue ( );    return startfloat + fraction * (Endvalue.floatvalue ()-startfloat);}

The parameters are the interpolation factor for the previous step, the start value and the end value, respectively.

3.2 Valueanimator

Valueanimator contains all the core functions of the property animation animation, such as animation time, start, end attribute value, corresponding time attribute value calculation method, and so on. The Application property animation has two steps to gather:

    1. Calculate attribute values
    2. Performs a corresponding action based on the value of the property, such as altering an object's properties.

Valuanimiator only completed the first step of the work, if you want to complete the second step, you need to implement the Valueanimator.onupdatelistener interface, this interface only a function onanimationupdate (), In this function, the Valueanimator object is passed as a parameter, and the current property value can be obtained through the Getanimatedvalue () function of the Valueanimator object, such as:

Valueanimator animation = Valueanimator.offloat (0f, 1f);
Animation.setduration (1000);
Animation.addupdatelistener (New Animatorupdatelistener () {
@Override
public void Onanimationupdate (Valueanimator animation) {
LOG.I ("Update", ((Float) Animation.getanimatedvalue ()). ToString ());
}
});
Animation.setinterpolator (New Cycleinterpolator (3));
Animation.start ();

In this example, just output some information to logcat and you can change the work you want to do.

Animator.animatorlistener

Onanimationstart () Onanimationend () onanimationrepeat ()//is called when the animation is canceled, and Onanimationend () is called. Onanimationcancel ()

Valueanimator.animatorupdatelistener

Onanimationupdate ()//By listening to this event when the value of the property is updated to perform the corresponding action, for valueanimator generally listen to this event to perform the corresponding action, otherwise animation meaningless, Properties are automatically updated in Objectanimator (inherited from Valueanimator), and you do not have to listen if necessary. A valueanimator parameter is passed in the function, and the current animation property value is obtained by Getanimatedvalue () of this parameter.

It is possible to simplify operations by inheriting Animatorlisteneradapter instead of implementing the Animatorlistener interface, which defines an empty function body for functions in Animatorlistener. This allows us to define only an empty function body by defining the events we want to listen to without implementing each function.

Objectanimator oa=objectanimator.offloat (TV, "Alpha", 0f, 1f); oa.setduration; Oa.addlistener (new Animatorlisteneradapter () {public    void on animationend (Animator animation) {        log.i ("animation", "End");}    }); o A.start ();
3.3 Objectanimator

Inherited from Valueanimator, to specify an object and a property of the object, when the property value calculation is completed automatically set to the corresponding property of the object, that is, the completion of the properties animation all two steps. In practice, Objectanimator is used to change a certain property of an object, but with objectanimator there are certain limitations, if you want to use Objectanimator, the following conditions should be met:

    • Object should have a setter function:set<propertyname> (hump naming method)
    • As in the above example, a factory method such as Offloat, the first parameter is the object name, the second is the property name, the following argument is a variable parameter, if values ... If the parameter is set to only one value, then it is assumed to be the destination value, the range of the property value is the current value to the destination value, in order to obtain the current value, the object has the corresponding property of the Getter method:get<propertyname>
    • If there is a getter method, it should return a value type that corresponds to the parameter type of the corresponding setter method.

If the above conditions are not satisfied, you can not use Objectanimator, apply Valueanimator instead.

tv= (TextView) Findviewbyid (r.id.textview1); btn= (Button) Findviewbyid (R.id.button1); Btn.setonclicklistener (new  Onclicklistener () {@Override public void OnClick (View v) {objectanimator oa=objectanimator.offloat (TV, "Alpha", 0f,    1f);    Oa.setduration (3000);  Oa.start (); }});

Change the transparency of a textview from 0 to 1 in 3 seconds.

Depending on the object or property that the animation is applied to, you may need to call the invalidate () function in the Onanimationupdate function to refresh the view.

3.4 Applying multiple animations via Animationset

Animationset provides a mechanism for combining multiple animations into one, and sets the timing relationships of the animations in the group, such as simultaneous playback, sequential playback, and so on.

The following example applies 5 animations at a time:

    1. Play anim1;
    2. simultaneous playback of ANIM2,ANIM3,ANIM4;
    3. 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 ();
3.5 typeevalutors

Based on the starting and ending values of the attributes and the factors computed by the timeinterpolation, the current time property values are calculated, and Android offers the following evalutor:

    • Intevaluator: The value type of the property is int;
    • Floatevaluator: The value type of the property is float;
    • Argbevaluator: The value type of the property is a hexadecimal color value;
    • Typeevaluator: An interface that can be customized evaluator by implementing the interface.

Customizing the Typeevalutor is simple, just implement a method, such as the definition of floatevalutor:

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);}    }

Depending on the time the animation executes and the interplator applied, a factor between the 0~1 is calculated, that is, the fraction parameter in the Evalute function, which should be well understood by the above Floatevaluator.

3.6 Timeinterplator

Time Interplator defines how property values change, such as a linear uniform change, starting slowly and then gradually getting faster. In the property animation is Timeinterplator, in the View animation is Interplator, these two are the same, The implementation code was transferred to Timeinterplator only after interplator,3.0 3.0. Interplator inherits from Timeinterplator, without any other code inside.

    • Accelerateinterpolator acceleration, slow intermediate acceleration at start
    • Decelerateinterpolator slow down, start fast and slow down.
    • Acceleratedecelerateinterolator acceleration and deceleration, slow start, middle acceleration
    • Anticipateinterpolator reverse, first change to the opposite direction and then accelerate the playback
    • Anticipateovershootinterpolator reverse add rebound, first change in the opposite direction, and then accelerate the play, will exceed the target value and then slowly move to the destination value
    • Bounceinterpolator jump, fast to the destination value will jump, such as the destination value of 100, followed by the value may be 85,77,70,80,90,100
    • Cycleiinterpolator cycle, animation cycle a certain number of times, the value is changed to a sine function: Math.sin (2 * mcycles * Math.PI * input)
    • Linearinterpolator linear, linear uniform change
    • Overshottinterpolator rebound, finally exceeding the target value and then slowly changing to the destination value
    • Timeinterpolator an interface that allows you to customize the Interpolator, the above several are implemented by this interface
3.7 Applying animations when layout changes

Child elements in ViewGroup can be visible, invisible, or GONE by setvisibility, and can be animated when there is a change in the visibility of child elements (visible, GONE). This type of animation is applied through the Layouttransition class:

Transition.setanimator (layouttransition.disappearing, Customdisappearinganim);

With Setanimator applied animations, the first parameter represents the context of the application and can be 4 types:

    • Appearing applies an animation to an element when it becomes visible in its parent element
    • Change_appearing when an element becomes visible in its parent element, there are elements that need to be moved as the system is re-layout, applying animations to the elements to be moved
    • Disappearing apply animation to an element when it becomes gone in its parent element
    • Change_disappearing when an element becomes gone in its parent element, the elements to be moved are animated as the system is re-layout with some elements that need to be moved.

The second parameter is a animator.

Mtransitioner.setstagger (layouttransition.change_appearing, 30);

This function sets the animation delay time, and the parameters are type and time, respectively.

3.8 Keyframes

Keyframe is a time/value pair that allows you to define a specific state at a specific time, that is, a keyframe, and you can define different interpolator between the two keyframe, as if multiple animations are stitched together, and the end point of the first animation is the start point of the second animation. Keyframe is an abstract class, to get the proper keyframe through Ofint (), Offloat (), Ofobject (), The Propertyvaluesholder object is then obtained through Propertyvaluesholder.ofkeyframe, as in the following example:

Keyframe kf0 = keyframe.ofint (0, 400); Keyframe Kf1 = Keyframe.ofint (0.25f, 200); Keyframe Kf2 = Keyframe.ofint (0.5f, 400); Keyframe Kf4 = Keyframe.ofint (0.75f, 100); Keyframe Kf3 = Keyframe.ofint (1f, 500); Propertyvaluesholder pvhrotation = propertyvaluesholder.ofkeyframe ("width", kf0, Kf1, Kf2, Kf4, KF3); objectanimator Rotationanim = Objectanimator.ofpropertyvaluesholder (btn2, pvhrotation); Rotationanim.setduration (2000);

The code above means: Set the value of the width property of the Btn object so that it:

    • Width=400 at the beginning
    • Animation starts at 1/4 width=200
    • Animation starts at 1/2 width=400
    • Animation starts at 3/4 width=100
    • Width=500 at the end of the animation
The first parameter is the percent of time, and the second parameter is the property value at the time of the first parameter. After defining some keyframe, a Propertyvaluesholder object is ofkeyframe by means of the Propertyvaluesholder class. A animator object is then obtained through Objectanimator.ofpropertyvaluesholder. The same effect can be achieved with the following code (the time value of the above code is linear and evenly varying):
Objectanimator Oa=objectanimator.ofint (btn2, "width", 400,200,400,100,500);
Oa.setduration (2000);
Oa.start ();
3.9 Animating views

In view animation, the view application animation does not change the view's properties, the animation is implemented through its parent view, and parents view changes its drawing parameters when the view is drawn. Draw and then change the parameter invalidate, so that although the size of the view or rotation angle changes, but the actual properties of the view has not changed, so the effective area is still applied before the animation area, such as you have a button to enlarge twice times, but still zoom in front of the area can trigger the Click event. To change this, add some parameters to the view in Android 3.0 and add the corresponding Getter/setter function to these parameters (Objectanimator to change these properties with these functions):

    • Translationx,translationy:view offset relative to the original position
    • Rotation,rotationx,rotationy: Swivel, rotation for 2D rotation angle, 3D for the latter two
    • Scalex,scaley: Zoom ratio
    • The final coordinate of the X,y:view is the left,top position of the view plus the Translationx,translationy
    • Alpha: Transparency
There are 3 parameters associated with the position, taking the X coordinate as an example, can be obtained by GetLeft (), GetX (), Gettranslatex (), if there is a button btn2, the coordinates of the layout are (40,0):
Before applying animations
Btn2.getleft (); 40
Btn2.getx (); 40
Btn2.gettranslationx (); 0
Apply Translationx Animations
Objectanimator oa=objectanimator.offloat (btn2, "Translationx", 200);
Oa.setduration (2000);
Oa.start ();
/* After applying Translationx animations
Btn2.getleft (); 40
Btn2.getx (); 240
Btn2.gettranslationx (); 200
*/
Apply the X animation, assuming that the previous Translationx animation was not applied
Objectanimator oa=objectanimator.offloat (BTN2, "X", 200);
Oa.setduration (2000);
Oa.start ();
/* After applying x animation
Btn2.getleft (); 40
Btn2.getx (); 200
Btn2.gettranslationx (); 160
*/
No matter how the animation is applied, the position of the original layout is obtained by GetLeft (), and the X is the final position of the view; Translationx is the difference between the final position and the initial position of the layout. So if you use Translationx to move how much on the original basis, X is the final number of GetX () and the value of GetLeft () and Gettranslationx () and for the X animation, the source code is this:
Case X:
Info.mtranslationx = Value-mview.mleft;
Break

Property animation can also be defined in XML

    • <set>-Animatorset
    • <animator>-Valueanimator
    • <objectAnimator>-Objectanimator
The XML file should be magnified in/res/animator/, and the animation is applied in the following ways:
Animatorset set = (Animatorset) animatorinflater.loadanimator (Mycontext, r.anim.property_animator);
Set.settarget (MyObject);
Set.start ();
3.10 Viewpropertyanimator

If you need to animate multiple properties of a view, you can use the Viewpropertyanimator class, which optimizes multi-attribute animations, merging some invalidate () to reduce the refresh view, which is introduced in 3.1.

The following two pieces of code achieve the same effect:

Propertyvaluesholder PVHX = propertyvaluesholder.offloat ("x", 50f);
Propertyvaluesholder pvhy = propertyvaluesholder.offloat ("y", 100f);
Objectanimator.ofpropertyvaluesholder (MyView, PVHX, Pvyy). Start ();
Myview.animate (). x (50f). Y (100f);

Android Animation Learning Note-android 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.