Android Properties Animation (property Animation) Full Parse (top)

Source: Internet
Author: User

Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/38067475

1. Overview

Android offers several types of animations: View Animation, drawable Animation, property Animation. The View animation is fairly simple, but only supports simple zooming, panning, rotation, transparency, and basic animations with some limitations. For example: you want the view to have a color switch animation, you want to be able to use the 3D rotation animation, you want to when the animation stops, the location of the view is the current position, these view animation can not do. This is the reason why property animation, this blog details the use of property animation. As for drawable Animation, uh, slightly ~

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: Difference value, at first glance do not know what is, but I said Linearinterpolator, acceleratedecelerateinterpolator, we must know is what, define the rate of change of animation.

Repeat count and behavior: The number of repetitions, the repetition pattern, the number of repetitions that can be defined, the beginning or the reverse of repetition.

Animator sets: A collection of animations, you can define a set of animations, execute them together, or execute them sequentially.

Frame Refresh delay: frame flush delay, for your animation, how often to refresh the frame, the default is 10ms, but ultimately dependent on the current state of the system, basically no tube.

Related classes

Objectanimator animation of the execution class, followed by detailed introduction

Valueanimator animation of the execution class, followed by detailed introduction

Animatorset is used to control the execution of a set of animations: linear, together, each animation is executed successively, and so on.

Animatorinflater XML file for user-loaded property animations

Typeevaluator type valuation, which is used primarily to set the value of an animation Action property.

Timeinterpolator time interpolation, described above.

In general, property animation is the execution class of an animation that sets the properties of an Animated object, the duration, the start and End property values, the time difference, and so on, and then the system dynamically changes the properties of the object according to the parameters set.

3, objectanimator realization animation

The reason why choose Objectanimator as the first ~ ~ is because, this implementation is the simplest ~ ~ a line of code, seconds to implement animation, see an example:
Layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    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 simple, just a sister picture ~
Activity code:

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

Effect:

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

For Objectanimator

1, provides Ofint, Offloat, Ofobject, these methods are set animation action elements, action properties, animation start, end, and the middle of any property values.

When only one is set for a property value, the value of the property is assumed to be the beginning (Getpropname reflection gets), and then the value is set to the end point. If you set two, then one for the start, one for the end ~ ~ ~

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

2, if you manipulate the object of the property method inside, such as the above example of Setrotationx if the internal does not call the view redraw, then you need to manually call the following way.

Anim.addupdatelistener (New Animatorupdatelistener () {@Overridepublic void onanimationupdate (Valueanimator animation ) {//view.postinvalidate ();//view.invalidate ();}});
3, see the above example, because set the operation of the property only one, then if I want an animation can be able to reduce the view can be reduced, and can fade out (3 properties Scalex,scaley,alpha), only use Objectanimator?

The idea is not very good, may say use animatorset ah, this look is a bunch of animation plug together to execute, 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);});}

To set the property of the string, casually 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 manually call ~

Effect:

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 realize it ~ ~ can use their own objectanimator to try ~

4, in fact, there is a simpler way to achieve 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

Similar to objectanimator usage, simply look at the animated code moving vertically with view:

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

Give you the feeling is not, Pit Daddy Ah, this and valueanimator have yarn difference ~ But look closely, you see, there is no set the properties of the operation ~ ~ that is, the above code is not any effect, no property specified ~

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

Benefits: The properties of objects that do not need to be manipulated must have getter and setter methods, you can manipulate any property yourself based on the computed value of the current animation, and remember the previous example, "I want an animation that will allow the view to both shrink and fade out (3 properties Scalex,scaley, Alpha) "? This is actually the way to use ~

Instance:

Layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "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 buttons ~ Let's look at a free-falling 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 the Objectanimator, we set the update of the element property ourselves ~ Although there are several lines of code, it seems to be more flexible ~

Here is another example, if I want the ball parabolic motion "to achieve the effect of parabola, horizontal direction 100px/s, vertical acceleration 200px/s*s", analysis, seemingly only with time, but according to the change of time, the horizontal and vertical movement rate is different, how should we achieve it? It is time to rewrite typevalue, because we need to return to the object two values, x current position, and Y position at the same time.

Code:

/** * 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);});} 
As can be seen, because ofint,offloat and so can not be used, we have customized 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, an int; Rectf,rect also) pointf contains the current position of x, Y and then we get it in the listener and set the properties dynamically:

:


There are two iron balls of wood at the same time landing feeling ~ ~ Yes, I should get two balls ~~ps: If the physical formula is wrong, you don't see ha.

Custom Typeevaluator incoming generics can design their own beans according to their own needs.

Well, we have separately explained Valueanimator and Objectanimator implementation animation, the difference between the two, how to use the partial API to update the properties of their own performance, custom typeevaluator to achieve our needs, but we did not say how to design interpolation, In fact, I think that this interpolation default that a string of implementation of the class enough ~ ~ Very few, will go 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 elements, I may want to be a fade out of the effect, but ultimately to delete, not your transparency is not, but also occupy the position, so we need to know how to end the animation.

So we can 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 ();}

So you can listen to the beginning of the animation, end, canceled, repeat events ~ but sometimes feel, I just know the end of the line, 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, stops at the current position, and the end animation is directly to the final state.

6, the use of Animatorset

Instance:

Layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "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 in order"/> </linearlayout></relativel Ayout>

Keep Playing Ball ~

Code:

Package Com.example.zhy_property_animation;import Android.animation.animatorset;import Android.animation.objectanimator;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.view.animation.linearinterpolator;import Android.widget.imageview;public class AnimatorSetActivity Extends Activity{private ImageView mblueball; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.anim_set); mblueball = (ImageView) Findviewbyid (R.id.id _ball);} public void Togetherrun (view view) {Objectanimator anim1 = objectanimator.offloat (Mblueball, "ScaleX", 1.0f, 2f); O Bjectanimator anim2 = objectanimator.offloat (Mblueball, "ScaleY", 1.0f, 2f); Animatorset animset = new Animatorset (); Animset.setduration (); Animset.setinterpolator (new Linearinterpolator ()) ;//Two animations simultaneously execute Animset.playtogether (ANIM1, anim2); Animset.start ();} public void Playwithafter (view view) {Float CX = mblueball.getx (); Objectanimator anim1 = ObjectaniMator.offloat (Mblueball, "ScaleX", 1.0f, 2f); Objectanimator anim2 = Objectanimator.offloat (Mblueball, "ScaleY", 1.0f, 2f); Objectanimator anim3 = Objectanimator.offloat (Mblueball, "X", CX, 0f); Objectanimator anim4 = Objectanimator.offloat (Mblueball, "X", CX);/** * ANIM1,ANIM2,ANIM3 simultaneously executes * ANIM4 then executes */animatorset animset = new Animatorset (); Animset.play (anim1 ). with (ANIM2), Animset.play (ANIM2). with (ANIM3), Animset.play (ANIM4). After (ANIM3); animset.setduration (1000); Animset.start ();}}

Two effects were written:

First: Use Playtogether two animations at the same time, of course, there are playsequentially executed in turn ~ ~

Second: If we have a bunch of animations, how to use the Code control order, such as 1, 2 at the same time, 3 after 2, 4 before 1 wait ~ is the effect 2

One thing to note: Animset.play (). with (); It also supports chained programming, but don't try to be mad, like Animset.play (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, so trouble you follow the above example, write a few 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, but the core function is these ~ ~

Yes, if you use the SDK below 11, please import the Nineoldandroids animation library, the usage is basically exactly the same ~


SOURCE Click to download








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.