Android Attribute Animation (property Animation) completely parse (top)

Source: Internet
Author: User

Reprint please indicate source:

1. Overview

Android offers several types of animations: View Animation, drawable Animation, property Animation. The View animation is fairly simple and only supports simple zooming, panning, rotating, and transparency of the main animations. And there are certain limitations.

For example: you want the view to have a color toggle animation. You want to be able to rotate the animation using 3D, which you want when the animation stops. The location of the view is the current position; none of these view animation can be done.

This is the reason why property animation is produced. This blog details how to use the property animation.

As for drawable Animation. Yes, a little ~

2. Related API

Property animation The Name Incredibles is the animation to change the properties of the object, we first need to understand a few properties:

Duration duration of the animation, default 300ms.

Time Interpolation: Time difference value, at first glance do not know what is. But I said Linearinterpolator, acceleratedecelerateinterpolator, we must know what it is to do, define the rate of change in animation.

Repeat count and behavior: repeated times, as well as repeated patterns, the ability to define how many times to repeat, and start over again. or the reverse.

Animator Sets: Animation collection, you can define a set of animations. Run together or sequentially.

Frame Refresh delay: frame flush delay, for your animation, how often to refresh the frame, default feel 10ms, but finally rely on the current state of the system. Basically no tube.

Related classes

Objectanimator the running class of the animation. The following specific introduction

Valueanimator the running class of the animation. The following specific introduction

Animatorset is used to control the operation of a set of animations: linear, together, each animation successively running, etc.

Animatorinflater the XML file that the user loads the property animation into

Typeevaluator type valuation. Used primarily to set the value of an animation Action property.

Timeinterpolator time interpolation, described above.

Overall. Property animation is. The animation's run class sets the properties of an Animated object, the duration, the start and end of the property value, the time difference, and so on, and the system dynamically changes the properties of the object according to the parameters set.

3, objectanimator realization animation

The reason why choose Objectanimator for the first ~ ~ is because. This implementation is the simplest ~ ~ One line of code, second seconds to achieve animation. Here's a sample example:
Layout file:

<relativelayout xmlns:android= ""    xmlns:tools= "http// "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:id= "@+id/id_container" >    <imageview        android:id= "@+id/id_ball"        android:layout_ Width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_centerinparent= "true"        android:src= "@drawable/mv"         android:scaletype= "Centercrop"        android:onclick= "Rotateyanimrun"        / ></RelativeLayout>

Very easy, just a sister picture ~
Activity code:

Package Com.example.zhy_property_animation;import Android.animation.objectanimator;import; Import Android.os.bundle;import Android.view.view;public class Objectanimactivity extends activity{@ overrideprotected 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 ();}}


is not a line of code to achieve a simple animation ~ ~

For Objectanimator

1, provided the Ofint, Offloat, Ofobject. These are the elements that animate, the properties of the action, the beginning and end of an animation, and the arbitrary attribute values in the middle.

When the value of a property is set only one time, it will feel that the value of the property of course object is start (Getpropname reflection gets). The value is then set to the end point. Suppose you set two, then one is the beginning, the other is the end ~ ~ ~

During an animation update, the properties of the Setpropname update element are constantly called, all using Objectanimator to update a property, and must have getter (when setting a property value) and setter method ~

2. Assume that you manipulate the object's properties inside the method. For example, the Setrotationx assumes that no redraw of the view is invoked internally. You will need to call them manually in the following way.

Anim.addupdatelistener (New Animatorupdatelistener () {@Overridepublic void onanimationupdate (Valueanimator animation ) {//view.postinvalidate ();//view.invalidate ();}});
3, look at the above example, because the operation of the set of properties only one. So let's say I want an animation that will allow the view to both shrink and fade out (3 attribute Scalex,scaley,alpha). Just using Objectanimator?

The idea is not very good, may say use animatorset ah. This is a bunch of animation plug running together, but I have to use a Objectanimator instance to implement it ~ See the following code:

public void Rotateyanimrun (final view view) {Objectanimator Anim = objectanimator//.offloat (View, "Zhy", 1.0F,  0.0F) . setduration (+);//anim.start (); Anim.addupdatelistener (new Animatorupdatelistener () {@Overridepublic void Onanimationupdate (Valueanimator animation) {Float cval = (float) animation.getanimatedvalue (); View.setalpha (Cval); View.setscalex (Cval); View.setscaley (cval);});}

Put the string that sets the property. Write a property that the object does not have, that is, whether ~ ~ we only need it according to the time interpolation and duration calculation of that value, we call it ourselves ~


This example is to illustrate, sometimes change the idea not to be bound by the API, the use of some of the features provided by the API can also achieve fun effect ~ ~ ~

For example: you want to achieve the effect of parabola, horizontal direction 100px/s, vertical acceleration 200px/s*s, how to achieve it ~ ~ can use their own objectanimator to try ~

4. In fact there are simpler ways to implement an animation to change multiple effects: using Propertyvaluesholder

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 (+). Start ();

4, Valueanimator realization Animation

Very similar to the Objectanimator use method, simply look at the animation code moving vertically with view:

public void Verticalrun (view view) {Valueanimator animator = valueanimator.offloat (0, mscreenheight- Mblueball.getheight ()); Animator.settarget (Mblueball); animator.setduration (+). Start ();

The feeling of giving you is not. Hang Daddy. This and valueanimator have yarn difference ~ But careful look, you see will find. There is no property set for the action ~ ~ that is, the above code does not have any effect, no properties specified ~

This is the difference with Valueanimator: Valueanimator does not operate on attributes, you may ask what are the advantages? Do I have to set it up manually?

Pros: Properties of objects that do not need to be manipulated must have getter and setter methods, and you can manipulate whatever properties you want to do with the current animation's computed value. Remember the previous example, "I want an animation that will allow view to both shrink and fade out (3 properties Scalex,scaley,alpha)"? This is actually the way to use ~


Layout file:

<relativelayout xmlns:android= "" xmlns:tools= "http// "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:id="        @+id/id_container "> <imageview android:id=" @+id/id_ball "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:src= "@drawable/bol_blue"/> <linearlayout Andro        Id:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_alignparentbottom= "true" android:orientation= "Horizontal" > <button android:layout_width= "wrap_content" an droid:layout_height= "Wrap_content" android:onclick= "Verticalrun" android:text= "vertical"/> < Button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:o nclick= "Paowuxian" android:text= "throwLine "/> </LinearLayout></RelativeLayout> 
Top left corner a small ball, bottom two button~ we'll look at a free-fall code:

/** * Freefall * @param view */public void Verticalrun (view view) {Valueanimator animator = valueanimator.offloat (0, Mscreenhe Ight-mblueball.getheight ()); Animator.settarget (Mblueball); Animator.setduration (); start ();// Animator.setinterpolator (value) Animator.addupdatelistener (new Animatorupdatelistener () {@Overridepublic void Onanimationupdate (Valueanimator animation) {Mblueball.settranslationy ((Float) Animation.getanimatedvalue ())});}

Unlike Objectanimator, we set the update of the element properties ourselves ~ Though several lines of code. But it seems to improve flexibility ~

Here's another example. Suppose I want the ball parabolic motion "to achieve the effect of parabola, horizontal direction 100px/s, vertical acceleration 200px/s*s", analysis, it seems to only have a relationship with time. But according to the change of time. The horizontal and vertical movement rates are different. How are we supposed to make it? This is the time to rewrite Typevalue, because we are at the same time of change. Need to return to the object two values, x current position, y current position:


/** * parabola * @param view */public void Paowuxian (view view) {Valueanimator Valueanimator = new Valueanimator (valueanimator.setduration); Valueanimator.setobjectvalues (new PointF (0, 0)); Valueanimator.setinterpolator (New Linearinterpolator ()); Valueanimator.setevaluator (New typeevaluator<pointf > () {//fraction = t/duration@overridepublic PointF evaluate (float fraction, PointF startvalue,pointf endvalue) {LOG.E  (TAG, fraction * 3 + "");//x direction 200px/s, then y direction 0.5 * tpointf point = new PointF ();p oint.x = $ * fraction * 3;point.y = 0.5f * (fraction * 3) * (fraction * 3); return point;}}); Valueanimator.start (); Valueanimator.addupdatelistener (new Animatorupdatelistener () {@Overridepublic void Onanimationupdate (Valueanimator animation) {PointF point = (PointF) animation.getanimatedvalue (); Mblueball.setx ( Point.x); mblueball.sety (POINT.Y);});} 
Can see, because ofint,offloat and so can not be used, we have defined a typevalue, each time according to the current time to return a PointF object, (pointf and point difference is the unit of X, Y is a float, one is an int; Rectf,rect also) The pointf includes the current position of x, Y and then we get in the listener and dynamically set the properties:

There are two iron balls of wood with a feeling of landing at the same time ~ ~. I should've got two balls. ~~ps: If the physical formula is wrong, you don't see it.

Define your own Typeevaluator incoming generics can design a bean based on your own needs.

Well, we've already explained the valueanimator and Objectanimator implementation animations separately. The difference between the two, and how to use some APIs. Self-updating properties to achieve the effect of their own definition of typeevaluator to achieve our needs; but we did not say how to design interpolation, in fact, I think, this interpolation of the default string implementation of the class enough ~ ~ Very little, will own to design a super-perverted ~ hmm ~ so: slightly.

5. Listen for animated events

For animation, is generally a number of auxiliary effects, such as I want to delete an element, I may want to be a fade out effect, but finally still want to delete, not your transparency, but also occupy the position. So we need to know how the animation ends.

So we were able to add an animated listener:

public void FadeOut (view view) {Objectanimator Anim = objectanimator.offloat (Mblueball, "alpha", 0.5f); Anim.addlistener (New Animatorlistener () {@Overridepublic void Onanimationstart (Animator animation) {LOG.E (TAG, "Onanimationstart");} @Overridepublic void Onanimationrepeat (Animator animation) {//TODO auto-generated method STUBLOG.E (TAG, " Onanimationrepeat ");} @Overridepublic void Onanimationend (Animator animation) {LOG.E (TAG, "onanimationend"); ViewGroup parent = (ViewGroup) mblueball.getparent (); if (parent! = NULL) Parent.removeview (Mblueball);} @Overridepublic void Onanimationcancel (Animator animation) {//TODO auto-generated method STUBLOG.E (TAG, " Onanimationcancel ");}); Anim.start ();}

This will be able to listen to the beginning of the animation, end, canceled, repeated events ~ But sometimes feel, I just want to know the end, so long code I can not receive, then you can use Animatorlisteneradapter

Anim.addlistener (New Animatorlisteneradapter () {@Overridepublic 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 ~

Animator also has the Cancel () and End () methods: The Cancel animation stops immediately and stops at the current position. End animation directly to the last state.

6, the use of Animatorset


Layout file:

<relativelayout xmlns:android= "" xmlns:tools= "http// "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:id="         @+id/id_container "> <imageview android:id=" @+id/id_ball "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_centerinparent= "true" android:src= "@drawable/bol        _blue "/> <linearlayout android:layout_width=" fill_parent "android:layout_height=" Wrap_content " Android:layout_alignparentbottom= "true" android:orientation= "horizontal" > <button Android            Oid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:onclick= "TogetherRun"            android:text= "Simple multi-animation together"/> <button android:layout_width= "Wrap_content"         android:layout_height= "Wrap_content"   android:onclick= "Playwithafter" android:text= "multiple animations run sequentially"/> </linearlayout></relativel Ayout>

Keep Playing Ball ~


Package Com.example.zhy_property_animation;import Android.animation.animatorset;import Android.animation.objectanimator;import;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; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.anim_set); mblueball = (ImageView) Findviewbyid ( _ball);} public void Togetherrun (view view) {Objectanimator anim1 = objectanimator.offloat (Mblueball, "ScaleX", 1.0f, 2f); O Bjectanimator anim2 = objectanimator.offloat (Mblueball, "ScaleY", 1.0f, 2f); Animatorset animset = new Animatorset (); Animset.setduration (); Animset.setinterpolator (new Linearinterpolator ()) ;//Two animations run Animset.playtogether (anim1, anim2) at the same time; 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.offloa T (Mblueball, "X", CX);/** * ANIM1,ANIM2,ANIM3 run at the same time * ANIM4 then run */animatorset animset = new Animatorset (); ( ANIM1). With (ANIM2), (ANIM2). with (ANIM3), (ANIM4). After (ANIM3); animset.setduration (1000); Animset.start ();}}

Two effects were written:

First: Use Playtogether two animations to run at the same time, and of course playsequentially run in turn ~ ~

Second: Let's say we have a bunch of animations, how to use code control order, for example, at the same time, 3 after 2. 4 before 1 Wait ~ is the effect of 2

One thing to note: (). with (); also supports chained programming. But don't try to be mad. For Example (ANIM1). with (ANIM2). Before (ANIM3). before (ANIM5); This is not possible, the system will not be based on the long string you write to determine the order of succession. So please follow the example above to write a few more lines:

Well, because of the space ~ ~ About the property animation has a bit of knowledge:

1. xml File creation Property animation

2. Layout animation

3. The Animate method of view, etc.

Then consider writing to the next article. It's just the core function.

Yes, suppose you use the SDK below 11. Please import the Nineoldandroids animation library. The use of the method is basically consistent ~

Source code click to download

Android Attribute Animation (property Animation) completely parse (top)

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: 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.