Android Property Animation complete parsing (top), basic usage of initial knowledge property animation

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/43536355

It's cool to have some animations on your phone, so the Android system gives us two ways to animate at the very beginning, frame-wise (frame-by-frame animation) and motion tweens (tweened Animation). Frames-by-frame animations work very simply by splitting a complete animation into a single picture and then making them coherent to play, similar to how the animation works. Motion tweens are a series of animations that allow you to animate a view, including fading, zooming, panning, and rotating four of them.

However, since the Android 3.0 version, the system has provided us with a brand-new animation mode, attribute animation (property animation), it is very powerful, make up for the previous motion tween some flaws, almost can completely replace the tweened animation. For frames-by-frame animations and the use of tweened animations, I don't want to talk more, their technology is older, and the online material is also very much, so today the theme of this article is to the Android property animation to complete a full parse.

Why introduce attribute animations?

Android before the mechanism of motion tweens is actually quite sound, under the Android.view.animation package has a lot of classes can be used for us to operate, to complete a series of animation effects, such as the view to move, zoom, rotate and fade, And we can also use Animationset to combine these animation effects, in addition to the configuration of Interpolator to control the speed of animation and so on. So here you may have a question, since the previous animation mechanism is so sound, why also introduce property animation it?

In fact, the above so-called sound is relative, if your needs only need to move, zoom, rotate and fade the view, then the tweened animation is really good enough. But obviously, these features are not enough to cover all of the scenes, and once our needs are beyond the four actions of move, scale, rotate, and fade out of the view, the motion tween can no longer help us, meaning it has considerable limitations in terms of functionality and scalability, So let's take a look at the scenes that the tweened animations are not capable of.

Note that I used the "manipulate view" description when I introduced the tweened animation, and yes, the tweened animation only works on the view. That is, we can animate a button, a TextView, or even a linearlayout, or any other component that inherits from view, but if we want to animate a non-view object, I'm sorry, the tweened animation won't help. Maybe some friends will find it incomprehensible, how do I need to animate a non-view object? Here I give a simple example, for example, we have a custom view, in which a point object is used to manage coordinates, and then in the OnDraw () method, it is drawn according to the coordinate value of the point object. That is, if we can animate the point object, the entire custom view will have an animated effect. Obviously, a tweened animation does not have this function, which is its first flaw.

Then there is a flaw in the tweened animation, which is that it can only move, scale, rotate, and fade out of the four animation operations, if we want to be able to change the background color of the view dynamically? Unfortunately, we can only rely on ourselves to achieve. Frankly speaking, the previous motion tween mechanism is the use of hard-coded way to complete, the function is limited to death is these, basically there is no extensibility to speak of.

Finally, the tweened animation has a fatal flaw, that is, it just changes the view display effect, and does not really change the view properties. What do you mean? For example, now there is a button in the upper left corner of the screen, and then we move it through the motion tween to the lower right corner of the screen, now you can try to click this button, click the event is absolutely not triggered, because the button is actually stuck in the upper left corner of the screen, Only the Tweened animation draws this button to the lower right corner of the screen.

It is for these reasons, the Android development team decided to introduce the feature animation in the 3.0 version of the function, then the property animation is not to solve all the above problems? Let's take a look at it.

The newly introduced property animation mechanism is no longer designed for view, and is not limited to moving, zooming, rotating, and fading, but is no longer just a visual animation effect. It is actually a mechanism for constantly manipulating values and assigning values to the specified properties of a specified object, which can be any property of any object. So we can still move or scale a view, but we can also animate the point object in the custom view. We just need to tell the system how long the animation is running, what type of animation to perform, and the initial and end values of the animation, and the rest of the work can be left to the system to complete.

Since the implementation mechanism of the property animation is achieved by assigning the target object and modifying its properties, the problem of the previously mentioned button display is no longer present, and if we move a button through the property animation, then the button is really moving, and it is not just drawn in another position.

Well, introduced so much, I believe that we have a basic understanding of attribute animation, the following we will begin to learn the use of property animation.

Valueanimator

Valueanimator is the most central class of the entire property animation mechanism, as we have already mentioned, the mechanism of property animation is implemented by constantly manipulating values, and the animation transitions between the initial and end values are computed by the Valueanimator class. It internally uses a mechanism of time loops to calculate the animation transitions between values and values, and we only need to provide the initial and end values to Valueanimator, and tell it how long the animation needs to run, Then Valueanimator will automatically help us with the effect of smoothing the transition from the initial value to the end value. In addition, Valueanimator is also responsible for managing animation playback times, playback modes, and setting listeners for animations, which is really a very important class.

But the usage of valueanimator is not complicated at all, let's start with the simplest function, for example, if you want to transition a value from 0 to 1, for 300 milliseconds, you can write:

Valueanimator anim = Valueanimator.offloat (0f, 1f); Anim.setduration (+); Anim.start ();
What do you think? Very simple, call Valueanimator's Offloat () method to build a Valueanimator instance, the Offloat () method allows to pass in multiple types of float parameters, where passing in 0 and 1 means that the value from 0 smooth transition to 1, Then call Valueanimator's Setduration () method to set the length of time the animation will run, and finally call the start () method to start the animation.

The usage is so simple, now if you run the code above, the animation will be executed. But this is just a transition from 0 to 1 of the animation, and do not see any interface effects, how can we know that the animation is really running it? This needs to be done with a listener, as follows:

Valueanimator anim = Valueanimator.offloat (0f, 1f); anim.setduration; Anim.addupdatelistener (new Valueanimator.animatorupdatelistener () {    @Override public    void Onanimationupdate (Valueanimator animation) {        float CurrentValue = (float) animation.getanimatedvalue ();        LOG.D ("TAG", "cuurent value is" + CurrentValue);    }); Anim.start ();
As you can see, here we add an animated listener through the Addupdatelistener () method, and we will continue to make callbacks during the execution of the animation, we just need to take the current value out of the callback method and print it out, we can know whether the animation is really running. To run the above code, the console prints as follows:


From the print log value we can see that the valueanimator is really working, the value in 300 milliseconds from 0 smooth transition to 1, and this calculation work is done by Valueanimator to help us. In addition the Offloat () method can be passed in any number of parameters, so we can also build more complex animation logic, such as a value in 5 seconds from 0 to 5, then transition to 3, and then transition to 10, you can write:

Valueanimator anim = Valueanimator.offloat (0f, 5f, 3f, 10f); anim.setduration (+); Anim.start ();
Of course you don't need a decimal number for the animation transition, maybe you just want to transition an integer value from 0 smooth to 100, then it's also very simple, just call Valueanimator's Ofint () method, as follows:
Valueanimator anim = valueanimator.ofint (0, 100);
Valueanimator the most commonly used should be offloat () and Ofint () These two methods, there is a ofobject () method, I will explain in the next article.

In addition, we can also call the Setstartdelay () method to set the time for the animation to delay playback, call the Setrepeatcount () and Setrepeatmode () methods to set the number of times the animation loops and the mode of the loop to play, The cycle mode includes restart and reverse two, which indicate the meaning of replay and reverse playback respectively. These methods are very simple, I will not go into the detailed explanation.

Objectanimator

The class that we are most exposed to is probably the same as Valueanimator,objectanimator, because Valueanimator is just a smooth animation transition to a value, but we don't seem to have much of a scene that actually uses this functionality. And Objectanimator is different, it can be directly to any object of arbitrary properties of animation operations, such as the view of the Alpha property.

However, although Objectanimator will be more commonly used, but it is actually inherited from the Valueanimator, the underlying animation implementation mechanism is based on valueanimator to complete, So Valueanimator is still the most central class in the entire property animation. So since it is an inheritance relationship, the methods that can be used in valueanimator can be used normally in objectanimator, and their usage is very similar, if we want to make a textview in 5 seconds from the normal transformation to be transparent, And then from full transparency to conventional, you can write this:

Objectanimator animator = Objectanimator.offloat (TextView, "Alpha", 1f, 0f, 1f); animator.setduration (5000); Animator.start ();
As you can see, we have called the Offloat () method to create an instance of Objectanimator, except that the parameters received in the Offloat () method have changed a little. The first parameter here requires passing in an object object, and we want to animate which object to pass in, and here I pass in a textview. The second parameter is what property of the object you want to animate, because we want to change the opacity of the TextView, so we pass in "alpha" here. After the argument is not fixed length, want to complete what kind of animation passed in what value, here the value of the TextView from the general transformation to transparent, and then from the full transparent transformation into the general. Then call the Setduration () method to set the duration of the animation, and then call the start () method to start the animation, as shown in the effect:


After learning this one usage, we can extrapolate the other usage, for example, we want to make the TextView a 360 degree rotation, we can write:

Objectanimator animator = Objectanimator.offloat (TextView, "rotation", 0f, 360f); animator.setduration (5000); Animator.start ();
As you can see, here we change the second parameter to "rotation" and then set the initial and end values of the animation to 0 and 360, and now run the code as shown:


So if you want to move the TextView out of the screen first and then back, you can write:

float Curtranslationx = Textview.gettranslationx (); Objectanimator animator = Objectanimator.offloat (TextView, " Translationx ", Curtranslationx, -500f, Curtranslationx); Animator.setduration (the); Animator.start ();
Here we first call the TextView's Gettranslationx () method to get to the location of the current TextView Translationx, and then the second parameter of the Offloat () method passes in "Translationx", The next three parameters are used to tell the system how the TextView should move, and now run the code, as shown in the following:


Then we can also textview the scaling operation, for example, the TextView in the vertical direction to enlarge 3 times times and then restore, you can write:

Objectanimator animator = Objectanimator.offloat (TextView, "ScaleY", 1f, 3f, 1f); animator.setduration (5000); Animator.start ();
Here, the second parameter of the Offloat () method is changed to "ScaleY", which means scaling in the vertical direction, and now rerun the program, as shown in the following:


So far, the use of Objectanimator is quite simple, but I believe there will be a lot of friends now in the heart of the same question, that is the Offloat () method of the second parameter in the end can be passed which values? Now that we've used the values alpha, rotation, Translationx, and ScaleY, which can be used to fade, rotate, move horizontally, and scale vertically, what other values are available? In fact, the answer to this question is very iffy, that is, we can pass in any value to the second parameter of the Offloat () method. Any of the values? I believe this is quite unexpected, but the truth is. Because Objectanimator is not designed for view at design time, but for any object, it is responsible for constantly assigning values to an attribute in an object, and then deciding how to show it based on the change of the property value.

So let's say we call the following code:

Objectanimator.offloat (TextView, "Alpha", 1f, 0f);
In fact, this code means that Objectanimator will help us to constantly change the value of the Alpha attribute in the TextView object, from 1f to 0f. The TextView object then needs to constantly refresh the display of the interface based on the change in the Alpha attribute value, allowing the user to see the fade animation.

So is there a value for the alpha attribute in the TextView object? No, not only does the TextView not have this attribute, even all of its parent classes do not have this attribute! It's strange that there is no alpha attribute in TextView and how does Objectanimator work? In fact, objectanimator internal working mechanism is not directly to our incoming property name operation, but will look for the property name corresponding to the get and set method, so the Alpha property corresponding to the get and set method should be:

public void Setalpha (float value);p ublic float getalpha ();
So are there these two methods in the TextView object? Yes, and these two methods are provided by the View object, which means that not only TextView can use this property for fade animation operations, any object that inherits from view can.

Since Alpha is like this, I believe you must already understand that all of the attributes we used earlier are the principle of this work, then there must be setrotation (), Getrotation (), Settranslationx (), Gettranslationx (), Setscaley (), Getscaley () These methods, if you don't believe, you can look in the view.

Combo Animations

The visual effects that stand-alone animations can achieve are, after all, quite limited, so it is especially important to combine multiple animations together for playback. Fortunately, the Android team also takes into account the features of the combo animation when designing property animations, so it provides a very rich set of APIs that let us combine multiple animations together.

The realization of the combined animation function primarily requires the use of the Animatorset class, which provides a play () method, if we pass a animator object (Valueanimator or Objectanimator) to this method An instance of Animatorset.builder will be returned, and the following four methods are included in the Animatorset.builder:

    • After (Animator anim) inserts an existing animation into the incoming animation after it executes
    • After (long delay) The existing animation is delayed by a specified millisecond after execution
    • Before (Animator Anim) executes an existing animation before inserting it into an incoming animation
    • With (Animator Anim) performs both existing and incoming animations

OK, with these four methods, we can complete the logic of the composition animation, so for example, we want to let textview move from the screen to the screen first, and then start to rotate 360 degrees, rotating the same time fade operation, you can write:

Objectanimator Movein = objectanimator.offloat (TextView, "Translationx", -500f, 0f); Objectanimator rotate = Objectanimator.offloat (TextView, "rotation", 0f, 360f); Objectanimator fadeinout = Objectanimator.offloat (TextView, " Alpha ", 1f, 0f, 1f); Animatorset animset = new Animatorset (); Animset.play (rotate). with (Fadeinout). After (Movein); Animset.setduration ( Animset.start ();
As you can see, we first create all three animated objects, then new out a Animatorset object to play the three animated objects, let the rotation and fade animation at the same time, and insert them behind the translation animation, and finally set the animation length and start animation. Run the above code as shown in the following:


Animator Listener

In many cases, we want to be able to hear the various events of the animation, such as when the animation starts, when it ends, and then performs some logical processing at the beginning or the end. This feature is fully achievable, and the animator class provides a AddListener () method that takes a animatorlistener, and we only need to implement this animatorlistener to listen to the various events of the animation.

As you already know, Objectanimator is inherited from Valueanimator, and Valueanimator is inherited from animator, So either Valueanimator or objectanimator can use the AddListener () method. In addition Animatorset is also inherited from the animator, so AddListener () This method is a common method.

The code for adding a listener is as follows:

Anim.addlistener (New Animatorlistener () {@Overridepublic void Onanimationstart (Animator animation) {} @Overridepublic void Onanimationrepeat (Animator animation) {} @Overridepublic void Onanimationend (Animator animation) {}@ overridepublic void Onanimationcancel (Animator animation) {}});
As you can see, we need to implement four methods in the interface, the Onanimationstart () method will be called at the beginning of the animation, and the Onanimationrepeat () method will be called when the animation is repeated, onanimationend () The method is called at the end of the animation, and the Onanimationcancel () method is called when the animation is canceled.

But maybe a lot of times we don't want to listen to so many events, maybe I just want to listen to the animation end of this event, it is very cumbersome to implement each of the four interfaces all over again. It doesn't matter, for this Android provides an adapter class, called Animatorlisteneradapter, using this class can solve the implementation of the interface cumbersome problems, as follows:

Anim.addlistener (New Animatorlisteneradapter () {});
Here we pass the adapter object to the AddListener () method, because each interface is already implemented in Animatorlisteneradapter, so there is no way to implement any of these methods without an error. So if I want to listen to the animation end of this event, just need to override this one method alone, as follows:
Anim.addlistener (New Animatorlisteneradapter () {@Overridepublic void Onanimationend (Animator animation) {}});
Animating with XML

We can use code to write all the animation features, which is also the most common practice. However, past tweened animations can also be written in XML in addition to coding, so property animations provide the ability to do the same with code-like property animations through XML.

Animating through XML can be slower than writing animations through code, but it can be very easy to reuse, such as writing a generic animation into XML, and then easily reusing it in various interfaces.

If you want to use XML to animate, first create a new animator folder under the Res directory, and all the property animation XML files should be stored in this folder. Then in the XML file we can use the following three kinds of tags:

    • <animator> valueanimator in the corresponding code
    • <objectAnimator> objectanimator in the corresponding code
    • <set> animatorset in the corresponding code

So let's say we want to achieve a smooth transition from 0 to 100, which can be written in XML:

<animator xmlns:android= "http://schemas.android.com/apk/res/android"    android:valuefrom= "0"    android: Valueto= "android:valuetype="    inttype "/>
And if we want to change the Alpha property of a view from 1 to 0, we can write this:
<objectanimator xmlns:android= "http://schemas.android.com/apk/res/android"    android:valuefrom= "1"    android:valueto= "0"    android:valuetype= "Floattype"    android:propertyname= "alpha"/>
In fact, the XML animation in terms of readability is still very high, the above content believe that I do not have to explain that everyone can read it.

In addition, we can use XML to complete complex animation operations, such as moving a view from the screen to the screen first, and then start rotating 360 degrees, rotating the same time fade operation, you can write:

<set xmlns:android= "http://schemas.android.com/apk/res/android" android:ordering= "sequentially" > <        Objectanimator android:duration= "android:propertyname=" Translationx "android:valuefrom="-500 " android:valueto= "0" android:valuetype= "floattype" > </objectAnimator> <set android:ordering            = "Together" > <objectanimator android:duration= "android:propertyname=" Rotation " android:valuefrom= "0" android:valueto= "android:valuetype=" "Floattype" > < /objectanimator> <set android:ordering= "sequentially" > <objectanimator Andro id:duration= "android:propertyname=" Alpha "android:valuefrom=" 1 "Android : valueto= "0" android:valuetype= "floattype" > </objectAnimator> <objectani Mator Android:duration= "Android:propertyname=" "Alpha" android:valuefrom= "0" Android:value to= "1" android:valuetype= "Floattype" > </objectAnimator> </set> </se T></set>
This XML implementation of the effect and we just implemented by the code to achieve the effect of the composite animation is exactly the same, each parameter meaning is very clear, I believe everyone is a look at the understanding, I will no longer one by one explained.

The final XML file is written, so how do we load the file into the code and start the animation? Just call the following code:

Animator Animator = animatorinflater.loadanimator (context, r.animator.anim_file); Animator.settarget (view); Animator.start ();
Call Animatorinflater's loadanimator to load the XML animation file, and then call the Settarget () method to set the animation to an object, and finally call the start () method to start the animation, it is so simple.

OK, through the study of this article, I believe that we have already had a very good understanding of the basic use of attribute animation, and the most commonly used to master some of the functions, then the content of this article is here, the next article will continue to introduce the property animation, To explain the advanced usage of valueanimator and objectanimator, please look forward to it.

First time to get blog update reminders, as well as more technical information sharing, welcome to follow my public number, sweep the QR code below or search number Guolin_blog, you can pay attention to.

Android Property Animation complete parsing (top), basic usage of initial knowledge property 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.