Basic tutorial for Android-attribute animation of Android animation collection-first sight

Source: Internet
Author: User

Basic tutorial for Android-attribute animation of Android animation collection-first sight
Basic tutorial for Android-attribute animation of Android animation collection-first sight

Tags (separated by spaces): basic Android tutorial

This section introduces:

This section introduces the third Animation in Android Animation-Property Animation ),
Remember to go To the Android basic getting started tutorial-8.4.2 Android animation set to Fragment
When setting the transition animation, we said that the Fragment under the App package and V4 package calls the corresponding setCustomAnimations ()
The animation types are different.AnimationIn the app packageAnimator;
AnimationThat's what we learned earlier.Frame Animation and compensation Animation!AnimatorThis section is aboutProperty Animation!
Uncle Guo has written three excellent summary articles about attribute animation, which are very good at writing and there is no need to repeat the wheel,
However, this is the case again. For most of the content, refer to the following three articles:
Complete parsing of Android property Animations (I): basic usage of property animations
Android property animation full parsing (medium), ValueAnimator, and ObjectAnimator advanced usage
Full parsing of Android property Animations (below), Interpolator and ViewPropertyAnimator usage
It is very well written, or you can skip this article to see the above three articles ~
Of course, you are welcome to read what I mean. Well, let's start this section ~

1. Attribute Animation

It's not BB. It's so violent ~

2. ValueAnimator for simple use

Procedure:

1. Call ValueAnimator's OfInt(), OfFloat() Or OfObject() Create a ValueAnimator instance using a static method. 2. Call the setXxx method of the instance to set the animation duration, interpolation method, and number of repetitions. 3. Call AddUpdateListenerAdd AnimatorUpdateListenerListener, in which
You can obtain the value calculated by ValueAnimator. You can apply the value to a specified object ~ 4. Call Start ()Method to enable animation!
In addition, we can see that both ofInt and ofFloat have such parameters: float/int... Values indicates multiple values!

Example:

Code Implementation:

Layout file:Activity_main.xml, Very simple, four buttons, one ImageView


  
   
   
   
      
   

NextMainActivity. java,
First, you need a method to modify the View position.MoveView() Set the start coordinates and width and height on the left and top!
Then we define four animations: moving straight lines, zooming, rotating transparent, and circular rotation!
Then, click the button to trigger the corresponding animation ~

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button btn_one; private Button btn_two; private Button btn_three; private Button btn_four; private LinearLayout ly_root; private ImageView img_babi; private int width; private int height; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. Activity_main); bindViews ();} private void bindViews () {ly_root = (LinearLayout) findViewById (R. id. ly_root); btn_one = (Button) findViewById (R. id. btn_one); btn_two = (Button) findViewById (R. id. btn_two); btn_three = (Button) findViewById (R. id. btn_three); btn_four = (Button) findViewById (R. id. btn_four); img_babi = (ImageView) findViewById (R. id. img_babi); btn_one.setOnClickListener (this); btn_two. SetOnClickListener (this); listener (this); btn_four.setOnClickListener (this); img_babi.setOnClickListener (this);} @ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_one: lineAnimator (); break; case R. id. btn_two: scaleAnimator (); break; case R. id. btn_three: raAnimator (); break; case R. id. btn_four: circleAnimator (); break; case R. id. img_babi: Toast. makeTex T (MainActivity. this, coder-pig ~, Toast. LENGTH_SHORT ). show (); break ;}}// defines a private void moveView (View view, int rawX, int rawY) to modify the ImageView position. {int left = rawX-img_babi.getWidth () /2; int top = rawY-img_babi.getHeight (); int width = left + view. getWidth (); int height = top + view. getHeight (); view. layout (left, top, width, height) ;}// method for defining attribute Animation: // follow the trajectory equation to motion private void lineAnimator () {width = ly_root.getWidth (); heigh T = ly_root.getHeight (); ValueAnimator xValue = ValueAnimator. ofInt (height, 0, height/4, height/2, height/4*3, height); xValue. setDuration (3000L); xValue. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {// trajectory equation x = width/2 int y = (Integer) animation. getAnimatedValue (); int x = width/2; moveView (img_babi, x, y) ;}}); XValue. setInterpolator (new LinearInterpolator (); xValue. start () ;}// the scaling effect is private void scaleAnimator () {// here we intentionally use two to show you how to use the combined animation ~ Final float scale = 0.5f; AnimatorSet scaleSet = new AnimatorSet (); ValueAnimator valueAnimatorSmall = ValueAnimator. ofFloat (1.0f, scale); valueAnimatorSmall. setDuration (500); ValueAnimator valueAnimatorLarge = ValueAnimator. ofFloat (scale, 1.0f); valueAnimatorLarge. setDuration (500); valueAnimatorSmall. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {float scale = (Float) animation. getAnimatedValue (); img_babi.setScaleX (scale); img_babi.setScaleY (scale) ;}}); valueAnimatorLarge. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {float scale = (Float) animation. getAnimatedValue (); img_babi.setScaleX (scale); img_babi.setScaleY (scale) ;}}); scaleSet. play (valueAnimatorLarge ). after (valueAnimatorSmall); scaleSet. start (); // you can actually do it with one. // ValueAnimator vValue = ValueAnimator. ofFloat (1.0f, 0.6f, 1.2f, 1.0f, 0.6f, 1.2f, 1.0f); // vValue. setDuration (1000L); // vValue. addUpdateListener (new ValueAnimator. animatorUpdateListener () {// @ Override // public void onAnimationUpdate (ValueAnimator animation) {// float scale = (Float) animation. getAnimatedValue (); // img_babi.setScaleX (scale); // img_babi.setScaleY (scale); //}); // vValue. setInterpolator (new LinearInterpolator (); // vValue. start ();} // The transparency changes while rotating. private void raAnimator () {ValueAnimator rValue = ValueAnimator. ofInt (1, 0,360); rValue. setDuration (1000L); rValue. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {int rotateValue = (Integer) animation. getAnimatedValue (); img_babi.setRotation (rotateValue); float fractionValue = animation. getAnimatedFraction (); img_babi.setAlpha (fractionValue) ;}}); rValue. setInterpolator (new DecelerateInterpolator (); rValue. start () ;}// round rotation protected void circleAnimator () {width = ly_root.getWidth (); height = ly_root.getHeight (); final int R = width/4; ValueAnimator tValue = ValueAnimator. ofFloat (0, (float) (2.0f * Math. PI); tValue. setDuration (1000); tValue. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {// circular parameter equation x = R * sin (t) y = R * cos (t) float t = (Float) animation. getAnimatedValue (); int x = (int) (R * Math. sin (t) + width/2); int y = (int) (R * Math. cos (t) + height/2); moveView (img_babi, x, y) ;}}); tValue. setInterpolator (new DecelerateInterpolator (); tValue. start ();}}

Okay, the process is very simple. First create the ValueAnimator object and call ValueAnimator. ofInt/ofFloat
And set the animation duration,AddUpdateListenerAddAnimatorUpdateListenerEvent listening,
Then use the parametersAnimationOfGetAnimatedValue() Get the current value, and then we can hold this value
In order to form the so-called animation effect, and then set the setInterpolator animation rendering mode,
Finally, call start () to start playing the animation ~
The slot, the linear equation, and the parameter equation of the circle have all started. Isn't that a high number,
Even the trigonometric function is forgotten when scientific slag is used...
For example, refer to github: MoveViewValueAnimator

3. simple use of ObjectAnimator

ObjectAnimator is easier to use than ValueAnimator.Direct
Animation of any attribute of any object! Yes, it is an arbitrary object, not just a View object,
Assign values to an attribute value of an object, and then determine how to display the attribute value of the object based on its changes.
Come out! For example, set the following animation for TextView:
ObjectAnimator. ofFloat (textview, "alpha", 1f, 0f );
Here, the alpha value is constantly changed from 1f-0f, and then the object is refreshed based on the changes in the attribute value.
It shows the effect of Fade-in and fade-out, but there is no alpha attribute in the TextView class. The internal mechanism of ObjectAnimator is as follows:
Find the get and set methods corresponding to the transmitted property names ~, Instead of looking for this attribute value!
If you don't believe it, you can go to the source code of TextView to check whether the alpha attribute exists!
Okay. Now let's use ObjectAnimator to implement the effects of four kinds of compensation animation ~

Run:

Code Implementation:

The layout directly uses the layout above, and adds a button to replace ImageView with TextView, so no code is pasted here,
Go directlyMainActivity. javaSome of the Code is actually quite the same ~

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button btn_one; private Button listener; private Button btn_three; private Button btn_four; private Button listener; private LinearLayout ly_root; private TextView TV _pig; private int height; private ObjectAnimator animator1; private ObjectAnimator animator2; private ObjectAnimator animator3; private Object Animator animator4; private AnimatorSet animSet; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bindViews (); initAnimator ();} private void bindViews () {ly_root = (LinearLayout) findViewById (R. id. ly_root); btn_one = (Button) findViewById (R. id. btn_one); btn_two = (Button) findViewById (R. id. btn_two); btn_thr Ee = (Button) findViewById (R. id. btn_three); btn_four = (Button) findViewById (R. id. btn_four); btn_five = (Button) findViewById (R. id. btn_five); TV _pig = (TextView) findViewById (R. id. TV _pig); height = ly_root.getHeight (); btn_one.setOnClickListener (this); listener (this); btn_four.setOnClickListener (this); listener (this); TV _pig. SetOnClickListener (this);} // initialize the animation private void initAnimator () {animator1 = ObjectAnimator. ofFloat (TV _pig, alpha, 1f, 0f, 1f, 0f, 1f); animator2 = ObjectAnimator. ofFloat (TV _pig, rotation, 0f, 360f, 0f); animator3 = ObjectAnimator. ofFloat (TV _pig, scaleX, 2f, 4f, 1f, 0.5f, 1f); animator4 = ObjectAnimator. ofFloat (TV _pig, translationY, height/8,-100, height/2);} @ Override public void onClick (V Iew v) {switch (v. getId () {case R. id. btn_one: animator1.setDuration (3000l); animator1.start (); break; case R. id. btn_two: animator2.setDuration (3000l); animator2.start (); break; case R. id. btn_three: animator3.setDuration (3000l); animator3.start (); break; case R. id. btn_four: animator4.setDuration (3000l); animator4.start (); break; case R. id. btn_five: // brings together the previous animation ~ AnimSet = new AnimatorSet (); animSet. play (animator4 ). with (animator3 ). with (animator2 ). after (animator1); animSet. setDuration (5000l); animSet. start (); break; case R. id. TV _pig: Toast. makeText (MainActivity. this is coder-pig ~, Toast. LENGTH_SHORT). show (); break ;}}}

The usage is also very simple. We will talk about the composite animation mentioned above ~

4. Combined animation and AnimatorListener

From the two examples above, we have all experienced a combination of animations and usedAnimatorSetThis class!
We call the play () method and pass in the first animation to start execution. At this time, he will return a Builder class to us:

Next, we can call the four methods provided by Builder to combine other animations:

After(Animator anim) insert an existing animation to the input animation and execute it. After(Long delay) specifies the animation latency to be executed within milliseconds. Before(Animator anim) inserts an existing animation into the input animation before it is executed. With(Animator anim) execute the existing animation and the imported animation at the same time.

Well, it's quite easy. Next we will talk about the animation event monitoring. The above ValueAnimator listener is
AnimatorUpdateListenerThe value will be called back when the status changes.OnAnimationUpdateMethod!
In addition to this kind of event, you can also listen to the animation status ~AnimatorListener, We can callAddListenerMethod
Add the listener and rewrite the following four callback methods:

OnAnimationStart (): Animation starts OnAnimationRepeat (): Repeated animation execution OnAnimationEnd (): Animation ends OnAnimationCancel (): Animation canceled

That's right. If you use the AnimatorListener, you must rewrite all the four methods. Of course, it is the same as the previous gesture section,
Android has provided us with an adapter class:AnimatorListenerAdapter, Each interface has been
All methods are implemented, so we can write only one callback method here!

5. Use XML to write animations

Using XML to write animations may take a longer time than Java code, but it is much easier to reuse it!
The corresponding XML labels are: <Animator> <ObjectAnimator> <Set>
The related attributes are described as follows:

Android: ordering: Specify the playing sequence of the animation: sequentially (sequential execution), together (simultaneous execution) Android: duration: Animation duration Android: propertyName= "X": Here is x. Do you still remember the "alpha" above? The object for loading the animation needs
Define the getx and setx methods. objectAnimator is used to modify the value of the object! Android: valueFrom= "1": initial animation start value Android: valueTo= "0": Final animation end value Android: valueType= "FloatType": the data type of the variable value.

Example:

Smooth transition animation from 0 to 100:

  

Change the alpha attribute of a view from 1 to 0.:


    
  

Set animation demo:


      
           
            
         
     
    
       
   
  

Load our animation files:

AnimatorSet set = (AnimatorSet)AnimatorInflater.loadAnimator(mContext,              R.animator.property_animator);  animator.setTarget(view);  animator.start();  
 

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.