Android full set of animation usage tips

Android full set of animation usage tips

[Quoted from MrXI's blog] 1. Android View Animation Framework

The Animation framework defines several common animations such as transparency, rotation, scaling, and displacement, and controls the entire View. The implementation principle is that each time a view is drawn, the drawChild function in the ViewGroup where the View is located obtains the Transformation value of the View's Animation, and then calls canvas.concat(transformToApply.getMatrix()) to complete the animation frame through matrix operations. If it is not completed, the invalidate() function is called to start the next drawing to drive the animation, thereby completing the drawing of the entire animation.

View animation is easy to use and has rich effects. It provides four animation methods: AlphaAnimation, RotateAnimation, TranslateAnimation, and ScaleAnimation, and provides an animation set AnimationSet, which can mix and use multiple animations. Before Android 3.0, view animation was the only one, but with the introduction of the attribute animation framework after Android 3.0, its popularity has declined. Compared with attribute animation, a very big flaw of view animation is that it is not interactive. When an element undergoes view animation, its position in response to the event is still where it was before the animation, so view animation can only produce ordinary animation effects to avoid interaction. But its advantages are also very obvious, that is, it is relatively efficient and easy to use.

View animation is very easy to use. Not only can you describe an animation process through XML files, you can also use code to control the entire animation process.

(1) Transparency animation

A transform animation that adds transparency to a view.

  1. AlphaAnimation aa = new AlphaAnimation(0, 1);
  2.  
  3. aa.setDuration(1000);
  4.  
  5. view .startAnimation(aa);

(2) Rotation animation

Adds a rotation transform animation to the view.

  1. RotateAnimation ra = new RotateAnimation(0, 360, 100, 100);
  2.  
  3. ra.setDuration(1000);
  4.  
  5. view .startAnimation(ra);

Its parameters are the starting angle of rotation and the coordinates of the rotation center point. Of course, the reference system of the rotation animation can be controlled by setting parameters. Here, the reference system of the rotation animation is set to the center.

  1. RotateAnimation ra1 = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5F, RotateAnimation.RELATIVE_TO_SELF, 0.5F);

(3) Displacement animation

Added translation animation when the view moves.

  1. TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 300);
  2.  
  3. ta.setDuration(1000);
  4.  
  5. view .startAnimation(ta);

(4) Zoom animation

Add animation effects to the scaling of views

  1. ScaleAnimation sa = new ScaleAnimation(0, 2, 0, 2);
  2.  
  3. sa.setDuration(1000);
  4.  
  5. view .startAnimation(sa);

Like the rotation animation, the scaling animation can also set the center point of Luo Fang, setting the center to the center effect

  1. ScaleAnimation sa1 = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5F, Animation.RELATIVE_TO_SELF, 0.5F);
  2.  
  3. sa1.setDuration(1000);
  4.  
  5. view .startAnimation(sa1);

(5) Animation Collection

Through AnimationSet, animation can be presented in a combined form:

  1. AnimationSet as = new AnimationSet( true );
  2.  
  3. as .setDuration(1000);
  4.  
  5. AlphaAnimation aa = new AlphaAnimation(0, 1);
  6.  
  7. aa.setDuration(1000);
  8.  
  9. as .addAnimation(aa);
  10.  
  11. RotateAnimation ra = new RotateAnimation(0, 360, 100, 100);
  12.  
  13. ra.setDuration(1000);
  14.  
  15. as .addAnimation(ra);
  16.  
  17. TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 300);
  18.  
  19. ta.setDuration(1000);
  20.  
  21. as .addAnimation(ta);
  22.  
  23. ScaleAnimation sa = new ScaleAnimation(0, 2, 0, 2);
  24.  
  25. sa.setDuration(1000);
  26.  
  27. as .addAnimation(sa);
  28.  
  29. view .startAnimation( as );

You can directly copy and run the code to see the effect!

For animation events, Android also provides corresponding listening callbacks, code:

  1. as .setAnimationListener(new Animation.AnimationListener() {
  2.  
  3. @Override
  4.  
  5. public void onAnimationStart(Animation animation) {
  6.  
  7. // animation starts
  8.  
  9. }
  10.  
  11. @Override
  12.  
  13. public void onAnimationEnd(Animation animation) {
  14.  
  15. //End of animation
  16.  
  17. }
  18.  
  19. @Override
  20.  
  21. public void onAnimationRepeat(Animation animation) {
  22.  
  23. // animation repeat
  24.  
  25. }
  26.  
  27. });

2. Attribute Animation

Because the existing animation framework Animation before Android 3.0 has some limitations - animation only changes the display and cannot respond to events. Therefore, after Android 3.0, Google proposed a new animation framework called attribute animation to achieve richer effects.

The most commonly used combination of AnimatorSet and ObjectAnimator in the Animator framework is ObjectAnimator for more refined control, controlling only one property value of an object, and combining multiple ObjectAnimators into AnimatorSet to form an animation. Moreover, ObjectAnimator can be driven automatically, and you can call setFrameDelay(long frameDelay) to set the interval time between animation frames. Most importantly, attribute animation truly controls the attribute value of a View by calling the get and set methods of the attribute, so the powerful attribute animation framework can basically achieve all animation effects.

(1) ObjectAnimator

ObjectAnimator is the most important implementation class in the property animation framework. To create an ObjectAnimator, you only need to use its static factory class to directly return an ObjectAnimator object. The parameters include an object and the name of the object's property, but this property must also have get and set functions. The set function will be called internally through the Java reflection mechanism to modify the object's property value. Similarly, you can also call setInterpolator to set the corresponding interpolator.

Next, imagine adding a translation animation to a Button. If you use the previous animation framework, the click event will not be triggered after translation. The effective click area is still the original location, and no click event will occur when you click the moved location. However, attribute animation is different. It actually changes the attributes of a View, so the event response area also changes. At this time, clicking the moved button will respond to the click event.

The property animation translation code is as follows:

  1. ObjectAnimator animator = ObjectAnimator.ofFloat(
  2.  
  3. imageView,
  4.  
  5. "translationX" ,
  6.  
  7. 200F);
  8.  
  9. animator.setDuration(300);
  10.  
  11. animator.start();

When using ObjectAnimator, it is very important that the properties to be manipulated must have get and set methods, otherwise ObjectAnimator will not work. The following are commonly used properties:

  • translationX and translationY: These two properties control the position of the View object from the top-left corner of its layout container as an increment.
  • rotation, rotationX, and rotationY: These three properties control the 2D and 3D rotation of the View object around the pivot.
  • scaleX and scaleY: These two properties control the 2D scaling of the View object around its pivot point.
  • pivotX and pivotY: These two properties control the pivot point of the View object, around which rotation and scaling transformations are performed. By default, the pivot point is the center point of the View object.
  • x and y: These two simple and practical properties describe the final position of the View object in its container. It is the accumulation of the initial upper left corner coordinates and the translationX and translationY values.
  • alpha: Indicates the alpha transparency of the View object. The default value is 1 (opaque), and 0 represents completely transparent (invisible).

According to the above, the animation effects achieved by view animation are basically included here.

So if an attribute does not have get and set methods, is the attribute animation helpless? The answer is no. Google provides two solutions to this problem at the application layer. One is to add get and set methods to this attribute indirectly by customizing an attribute class or wrapper class; or to implement it through ValueAnimator. ValueAnimator will be discussed in the following content. Let's first look at the method of using the wrapper class to add get and set methods to an attribute. The code is as follows:

  1. private static class WrapperView {
  2. private View mTarget;
  3.  
  4. public WrapperView( View mTarget) {
  5. this.mTarget = mTarget;
  6. }
  7.  
  8. public   int getWidth() {
  9. return mTarget.getLayoutParams().width;
  10. }
  11.  
  12. public void setWidth( int width) {
  13. mTarget.getLayoutParams().width = width;
  14. mTarget.requestLayout();
  15. }
  16. }

Through the above code, a layer of wrapping is added to a property, and get and set methods are provided for it. When using it, you only need to manipulate the wrapper class to indirectly call the get and set methods. The code is as follows:

  1. WrapperView wrapperView = new WrapperView( view );
  2.  
  3. ObjectAnimator.ofInt(wrapperView, "width" , 500).setDuration(5000).start();

(2) PropertyValuesHolder

Similar to AnimationSet in view animation, in property animation, if you want to apply multiple animations to multiple properties of the same object at the same time, you can use PropertyValuesHolder to achieve it. For example, if you want to change the scale of the X and Y axes at the same time during the translation process, you can do it like this:

  1. PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat( "translationX" , 300);
  2.  
  3. PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat( "scaleX" , 1f, 0, 1f);
  4.  
  5. PropertyValuesHolder pvh3 = PropertyValuesHolder.ofFloat( "scaleY" , 1f, 0, 1f);
  6.  
  7. ObjectAnimator.ofPropertyValuesHolder(pvh1, pvh2, pvh3).setDuration(1000).start();

In the code, the PropertyValuesHolder object is used to control the three properties of translationX, scaleX, and scaleY. The coolest method is to call the ObjectAnimator.ofPropertyValuesHolder method to realize the joint effect of multi-property animation. The whole implementation method is very similar to the use of AnimatorSet.

(3) ValueAnimator

ValueAnimator occupies a very important position in attribute animation. Although it is not as dazzling as ObjectAnimator, it is the core of attribute animation. ObjectAnimator also inherits from ValueAnimator.

  1. public final class ObjectAnimator extends ValueAnimator

ValueAnimator itself does not provide any animation effects. It is more like a value generator that generates numbers with a certain pattern, so that the caller can control the implementation process of the animation. The general usage of ValueAnimator is: usually listen to the change of the value in the AnimatorUpdateListener of ValueAnimator to complete the animation change.

  1. ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 100);
  2.  
  3. valueAnimator.setTarget(imageView);
  4.  
  5. valueAnimator.setDuration(1000).start();
  6.  
  7. valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  8.  
  9. @Override
  10.  
  11. public void onAnimationUpdate(ValueAnimator animation) {
  12.  
  13. Float value = ( Float ) animation.getAnimatedValue();
  14.  
  15. }
  16.  
  17. });

(4) Monitoring animation events

A complete animation has four processes: Start, Repeat, End, and Cancel. Android provides an interface to easily monitor these four events:

  1. ObjectAnimator anim = ObjectAnimator.ofFloat(imageView, "alpha" , 0.5F);
  2. anim.addListener(new Animator.AnimatorListener() {
  3. @Override
  4. public void onAnimationStart(Animator animation) {
  5.          
  6. }
  7.  
  8. @Override
  9. public void onAnimationEnd(Animator animation) {
  10.  
  11. }
  12.  
  13. @Override
  14. public void onAnimationCancel(Animator animation) {
  15.  
  16. }
  17.  
  18. @Override
  19. public void onAnimationRepeat(Animator animation) {
  20.  
  21. }
  22. });
  23. anim.start();

Most of the time, we only care about the onAnimationEnd event, so Android also provides an AnimatorListenerAdapter to let us select the necessary events to listen to:

  1. anim.addListener(new AnimatorListenerAdapter() {
  2. @Override
  3. public void onAnimationEnd(Animator animation) {
  4. super.onAnimationEnd(animation);
  5. }
  6. });

(***nimatorSet

For a property to have multiple property animation effects at the same time, we have used PropertyValuesHolder to achieve this effect. AnimatorSet can not only achieve this effect, but also achieve more precise sequence control. If we use AnimatorSet to achieve the same animation effect demonstrated above using PropertyValuesHolder, the code is as follows:

  1. ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "translationX" , 300f);
  2.  
  3. ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(imageView, "scaleX" , 1f, 0f, 1f);
  4.  
  5. ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(imageView, "scaleY" , 1f, 0f, 1f);
  6.  
  7. AnimatorSet animatorSet = new AnimatorSet();
  8.  
  9. animatorSet.setDuration(1000);
  10.  
  11. animatorSet.playTogether(objectAnimator, objectAnimator1, objectAnimator2);
  12.  
  13. animatorSet.start();

In attribute animation, AnimatorSet uses methods such as playTogether(), playSquentially(), animSet.play().width(), defore(), and after() to control the collaborative working mode of multiple animations, thereby achieving precise control over the animation playback order.

(6) Using attribute animation in XML

Property animation is the same as view animation, and can also be written directly in the XML file. The code is as follows:

  1. <?xml version= "1.0" encoding= "utf-8" ?>
  2.  
  3. <objectAnimator xmlns:android= "http://schemas.android.com/apk/res/android"  
  4.  
  5. android:duration= "1000"  
  6.  
  7. android:propertyName= "scaleX"  
  8.  
  9. android:valueFrom= "1.0"  
  10.  
  11. android:valueTo= "2.0"  
  12.  
  13. android:valueType= "floatType" >
  14.  
  15. </objectAnimator>

Prerequisite: Use XML to define attribute animation. The XML file must be placed in the res/animator/filename.xml folder to be recognized. Otherwise, it cannot be recognized. It is found that the writing methods of attribute animation and view animation in XML files are very similar. Use in the program:

  1. Animator anim = AnimatorInflater.loadAnimator(this,R.animator.filename);
  2.  
  3. anim.setTarget( view );
  4.  
  5. anim.start();

(7) View's animate method

After Android 3.0, Google added the animate method to View to directly drive attribute animation. The code is as follows:

  1. imageView.animate()
  2. .alpha(0)
  3. .y(300)
  4. .setDuration(300)
  5. .withStartAction(new Runnable() {
  6. @Override
  7. public void run() {
  8.  
  9. }
  10. })
  11. .withEndAction(new Runnable() {
  12. @Override
  13. public void run() {
  14. runOnUiThread(new Runnable() {
  15. @Override
  16. public void run() {
  17.                          
  18. }
  19. });
  20. }
  21. }).start();

3. Android layout animation

Layout animation is applied to ViewGroup, adding an animated transition effect when adding View to ViewGroup. The simplest layout animation is in the XML of ViewGroup, using the following code to turn on layout animation:

  1. android:animateLayoutChanges= "true"  

With the above settings, when ViewGroup is added to View, the child View will show a gradual display transition effect. However, this effect is the default display transition effect of Android and cannot be replaced by a custom animation.

You can also customize the transition effect of a sub-View by using the LayoutAnimatorController class and adding a view animation so that the sub-View appears with a scaling animation effect. The code is as follows:

  1. LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
  2. ScaleAnimation sa = new ScaleAnimation(0, 1, 0, 1);
  3. sa.setDuration(2000);
  4. //Set the display of layout animation
  5. LayoutAnimationController lac = new LayoutAnimationController(sa, 0.5f);
  6. //Set layout animation
  7. ll.setLayoutAnimation(lac);

The first parameter of LayoutAnimationController is the animation to be applied, and the second parameter is the delay time for each sub-View to be displayed. When the delay time is not 0, the order in which the sub-Views are displayed can be set.

  1. //order
  2.  
  3. public   static final int ORDER_NORMAL = 0;
  4.  
  5. //random
  6.  
  7. public   static final int ORDER_REVERSE = 1;
  8.  
  9. //Reverse order
  10.  
  11. public   static final int ORDER_RANDOM = 2;

4. Interpolators

Interpolators are a very important concept in animation. Through interpolators, the animation transformation rate can be defined, which is very similar to acceleration in physics. Its main function is to control the change value of the target variable to make corresponding changes.

  • AccelerateDecelerateInterpolator changes the rate slowly at the beginning and introduction of the animation, and accelerates in the middle
  • AccelerateInterpolator changes slowly at the beginning of the animation, then starts to accelerate
  • AnticipateInterpolator starts backwards and then swings forward
  • AnticipateOvershootInterpolator starts by going backwards and then forwards a certain value before returning the highest value.
  • BounceInterpolator bounces when the animation ends
  • CycleInterpolator The animation loops a specific number of times, with the rate changing along a sine curve.
  • DecelerateInterpolator is fast at the beginning of the animation and then slows down
  • LinearInterpolator changes at a constant rate
  • OvershootInterpolator throws forward a certain value and then returns to the original position
  • PathInterpolator

To be continued...

5. Open Source Code Library

*** I will share another code library that I have accumulated for a long time. There is nothing you can't think of and nothing you can't use. Welcome to star

https://github.com/xijiufu

Since the GitHub server is in the United States, sometimes the access is slow. We also provide an open source Chinese address library. The codes of the two repositories are updated synchronously:

http://git.oschina.net/xijiufu

<<:  It’s not easy for WebView to say I love you

>>:  Android sliding analysis and various implementations

Recommend

What exactly is the Huawei Matebook like?

Huawei is also going to release a notebook. This i...

Fenda was once very popular, but then faded out of users’ sight. Why?

In 2016, when knowledge payment platforms were on...

How can brands leverage marketing opportunities on Labor Day?

For a company, there are never enough festivals, ...

Brand marketing promotion: 6 tricks for brand naming!

01 The success of a big brand can cover up many i...

How to improve the conversion rate of new users?

We often say that while learning to maintain old ...

Short video competitor analysis

The short video field is undoubtedly the hottest ...