Detailed explanation of the use and properties of three types of animations in App development

Detailed explanation of the use and properties of three types of animations in App development

[[437158]]

This article is reprinted from the WeChat public account "Android Development Programming", the author is Android Development Programming. Please contact the Android Development Programming public account for reprinting this article.

Preface

This time we introduce the classification of animations in Android:

View Animation (tween animation);

Drawable Animation (frame animation);

Property Animation (property animation);

1. Frame Animation

Frame animation is to play a set of predefined pictures in sequence. Different from View animation, the system provides another class AnimationDrawable to use frame animation;

Frame animation, as the name implies, produces animation effects by playing pictures frame by frame in sequence, similar to playing a movie.

The disadvantage of this animation is obvious, that is, if the images are too large or too many, it will cause OOM. The frame animation xml file is placed in the drawable directory instead of the anim folder;

Use of frame animation

First, we find a set of frame animation pictures and put them in the drawable-xhdpi folder. Then, create an xml file in the drawable folder as shown below:

  1. <?xml version= "1.0" encoding= "utf-8" ?>
  2. <animation-list
  3. xmlns:android= "http://schemas.android.com/apk/res/android"  
  4. android:oneshot= "false" >
  5. <item android:drawable= "@drawable/refresh1" android:duration= "180" />
  6. <item android:drawable= "@drawable/refresh2" android:duration= "180" />
  7. ...
  8. <item android:drawable= "@drawable/refresh25" android:duration= "180" />
  9. </animation-list>
  10. view = findViewById(R.id.test);
  11. view .setBackgroundResource(R.drawable.drawable_test_anim);
  12. view .setOnClickListener(new View .OnClickListener() {
  13. @Override
  14. public void onClick( View v) {
  15. AnimationDrawable animationDrawable = (AnimationDrawable) view .getBackground();
  16. animationDrawable.start();
  17. }
  18. });

Attribute Introduction

  • <animation-list> must be the root node, containing one or more <item> elements, with the following attributes:
  • android:oneshot true means it is executed only once, false means it is executed repeatedly;
  • <item> is similar to a frame of animation resources;
  • <item> is a child of animation-list, and contains the following properties:
  • android:drawable A frame's Drawable resource;
  • android:duration How long a frame is displayed;

2. Tween animation

Tween animation is an animation effect achieved by rotating, scaling, gradient, and changing the transparency of the view;

It is a progressive animation. And you can complete complex custom animation effects by combining the above four operations;

The disadvantage is that it only changes the display state of the view, but does not change the position of the view;

  1. <?xml version= "1.0" encoding= "utf-8" ?>
  2. < set xmlns:android= "http://schemas.android.com/apk/res/android"  
  3. android:duration= "4000"  
  4. android:fillAfter= "true"  
  5. android:fillBefore= "true"  
  6. android:interpolator= "@[package:]anim/interpolator_resource"  
  7. android:repeatMode= "restart | reverse"  
  8. android:repeatCount = "0"
  9. android:shareInterpolator= "true"  
  10. android:startOffset= "float" >
  11. <alpha
  12. android:fromAlpha= "float"  
  13. android:toAlpha= "float" />
  14. <scale
  15. android:fromXScale= "float"  
  16. android:fromYScale= "float"  
  17. android:pivotX= "float"  
  18. android:pivotY= "float"  
  19. android:toXScale= "float"  
  20. android:toYScale= "float" />
  21. <rotate
  22. android:fromDegrees= "float"  
  23. android:pivotX= "float"  
  24. android:pivotY= "float"  
  25. android:toDegrees= "float" />
  26. <translate
  27. android:fromXDelta= "float"  
  28. android:fromYDelta= "float"  
  29. android:toXDelta= "float"  
  30. android:toYDelta= "float" />
  31. </ set >

General property description:

  • android:duration="" animation duration, in milliseconds
  • android:fillAfter="true" Whether the animation stays at the end position after completion, the default is false
  • android:fillBefore="true" Whether the animation stays at the starting point after completion. Default is true, and the priority is lower than fillAfter
  • android:interpolator is the speed of the animation change [can be set separately or placed directly in the set]
  • android:repeatMode="restart | reverse" animation repetition strategy restart repeats from the starting position (positive order), reverse repeats from the end position (reverse order)
  • android:repeatCount = "0" means the number of repetitions is "infinite" which means infinite repetition
  • android:shareInterpolator="true" Whether the animations in the animation set share a common interpolator
  • android:startOffset="float" animation delay time

Transparency animation

  • Transparency animation, display animation by changing the transparency of the view. Corresponding to AlphaAnimation and XML tags
  • android:fromAlpha="float" starting transparency, value range (-1.0~1.0)
  • android:toAlpha="float" Transparency at the end, value range (-1.0~1.0)

Scale Animation

  • Scaling animation, display animation by modifying the size of the view. Corresponding to ScaleAnimation class and XML expression
  • android:fromXScale="float" animation's starting scale factor in the horizontal direction X
  • android:fromYScale="float" animation ends at the horizontal Y scale factor
  • android:toXScale="float" animation ends at the vertical X scale factor
  • android:toYScale="float" animation's end scaling factor in the vertical direction Y
  • android:pivotX="float" x coordinate of the scaling center point
  • android:pivotY="float" scales the y coordinate of the center point

Rotation Animation

  • Display animation by rotating the view. Corresponding to the RotateAnimation class and xml tag
  • android:fromDegrees="float" The rotation angle of the view when the animation starts (positive = clockwise, negative = counterclockwise)
  • android:toDegrees="float" The rotation angle of the view when the animation ends (positive = clockwise, negative = counterclockwise)
  • android:pivotX="float" The x coordinate of the rotation center point is as explained above for the scaling center point parameters.
  • android:pivotY="float" The y coordinate of the rotation center point is as explained above for the scaling center point parameters.

Panning animation

  • Translate animation, change the view's display position to display animation. Corresponding to the TranslateAnimation class and XML expression
  • android:fromXDelta="float"view's starting value in the horizontal x direction
  • android:fromYDelta="float"view's starting value in the horizontal y direction
  • android:toXDelta="float"view's end value in the horizontal x direction
  • android:toYDelta="float" The end value of the view in the horizontal y direction

Use of specific animations

Apply animation xml configuration

  1. TextView textDemo = findViewById(R.id.text_demo);
  2. Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_animation_test);
  3. textDemo.startAnimation(animation);

Use java class to configure animation. The specific parameters are similar to xml parameters. It is recommended to use xml to configure animation

  1. AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 2.0f);
  2. textDemo.startAnimation(alphaAnimation);

Monitor animation

  1. alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
  2. @Override
  3. public void onAnimationStart(Animation animation) {
  4. //Animation start callback
  5. }
  6. @Override
  7. public void onAnimationEnd(Animation animation) {
  8. //Animation end callback
  9. }
  10. @Override
  11. public void onAnimationRepeat(Animation animation) {
  12. //Callback when animation repeats
  13. }
  14. });

3. Attribute animation

The essence of attribute animation is to achieve animation by changing the attributes of the object (for example, x, y, etc.), so it is basically omnipotent. As long as the object has this attribute, the animation effect can be achieved;

Property animation is a new feature in API 11, which achieves animation effects by dynamically changing the properties of a view. Although you can use the nineoldandroid library for backward compatibility, the compatibility is essentially achieved using tween animation, which means that the properties of the view will not be changed, nor will the position of the view be changed;

Commonly used classes for attribute animation: ValueAnimator, ObjectAnimator, AnimationSet, among which ObjectAnimator is a subclass of ValueAnimator, and AnminationSet is an animation set;

1. Single animation

  1. ObjectAnimator animator = ObjectAnimator
  2. .ofInt(textDemo, "backgroundColor" , 0XffFF0000, 0Xff0000FF)
  3. .setDuration(2000);
  4. animator.setRepeatMode(ValueAnimator.RESTART);
  5. animator.setRepeatCount(10);
  6. animator.start();

2. Animation Collection

  1. AnimatorSet animatorSet = new AnimatorSet();
  2. ValueAnimator translationX = ObjectAnimator.ofFloat(textDemo, "translationX" , 200f);
  3. ValueAnimator animator = ObjectAnimator
  4. .ofInt(textDemo, "backgroundColor" , 0XffFF0000, 0Xff0000FF);
  5. animatorSet.playTogether(translationX,animator);
  6. animatorSet.setDuration(1000).start();

Animation configuration can also be configured using XML;

3. Difference Analyzer and Estimator

Interpolator

Calculate the current attribute change percentage based on the percentage of time elapsed. Same as the android:interpolator attribute configuration in the xml animation configuration. Common ones include LinearInterpolator (linear interpolator), AccelerateDecelerateInterpolator (acceleration and deceleration interpolator), etc. Customization requires the implementation of Interpolator or TimeInterpolator. The Interpolator interface inherits TimeInterpolator;

  1. //Interpolator interface
  2. public interface Interpolator extends TimeInterpolator{
  3. // There is only one method inside
  4. float getInterpolation( float input) {
  5. // Parameter description
  6. // The input value range is 0-1, and changes evenly with the animation progress (0% - 100%)
  7. // When the animation starts, the input value = 0; when the animation ends, the input = 1
  8. // The middle value increases evenly between 0 and 1 as the animation progresses (0% - 100%)
  9. ...// Interpolator calculation logic
  10. return xxx;
  11. // The returned value is the fraction value used by the estimator to continue calculating, which will be explained in detail below
  12. }
  13. // TimeInterpolator interface
  14. // Same as above
  15. public interface TimeInterpolator {
  16. float getInterpolation( float input);
  17. }

TypeEvaluator

Calculate the changed property value based on the current property change percentage. Properties specific to property animation; custom estimators need to implement the TypeEvaluator interface;

  1. public interface TypeEvaluator {
  2. public Object evaluate( float fraction, Object startValue, Object endValue) {
  3. // Parameter description
  4. // fraction: the return value of the interpolator getInterpolation()
  5. // startValue: the initial value of the animation
  6. // endValue: the end value of the animation
  7. ....//Calculation logic of the estimator
  8. return xxx;
  9. // Specific values ​​assigned to animation properties
  10. // Use reflection mechanism to change property changes

You can animate any attribute. Attribute animation requires the object to provide get() and set() methods for the attribute. Because the essence of attribute animation is to calculate the attribute value based on the initial value and end value of the object attribute transmitted from the outside world, and then use the estimator and differencer to continuously call the attribute set method. The value transmitted over time is getting closer and closer to the end value.

Notice:

Object properties must provide corresponding set methods, and if no initial value is passed in, a get method must be set because the system needs to obtain the initial value. If the conditions are not met, the program cashes;

The set method of an object property changes the property, which needs to be expressed in some way. This changes the UI display effect. Otherwise, the animation will not take effect.

ValueAnimator

Use ValueAnimator to monitor the animation process and change the object properties to complete the animation

  1. ValueAnimator valueAnimator = ValueAnimator.ofInt(1, 100);
  2. valueAnimator.setDuration(2000); // animation duration
  3. valueAnimator.setRepeatCount(0);//Number of repetitions
  4. valueAnimator.setRepeatMode(ValueAnimator.REVERSE);//Repeat mode,
  5. valueAnimator.setStartDelay(20); //Delay time before starting
  6. valueAnimator.setEvaluator(new IntEvaluator()); //Evaluator
  7. valueAnimator.setInterpolator(new LinearInterpolator()); //Interpolator
  8. valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  9. @Override
  10. public void onAnimationUpdate(ValueAnimator animation) {
  11. //Get the current animation attribute value, which is 1~100
  12. Integer animatedValue = ( Integer ) animation.getAnimatedValue();
  13. //Get the animation percentage
  14. float animatedFraction = animation.getAnimatedFraction();
  15. ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
  16. int width = layoutParams.width;
  17. int height = layoutParams.height;
  18. layoutParams.height = height + 1;
  19. layoutParams.width=width+1;
  20. Log.e(TAG, "animatedValue: " +animatedValue+ " animatedFraction : " +animatedFraction
  21. + " width : " +layoutParams.width+ " height : " +layoutParams.height);
  22. textView.requestLayout();
  23. }
  24. });
  25. valueAnimator.start();
  26. }

IV. Precautions

OOM note, if the pictures are too large or there are too many pictures in the frame animation, it is easy to appear;

Memory leak, remember to stop the animation when the activity is destroyed. Otherwise, some infinite loop animations will cause the activity to not be released and memory leaks. This problem occurs in attribute animation, but not in view animation;

View animation is interpolation animation, which changes the visual position of the view and the image display position of the view without changing the real position. Pay attention to the interactive experience. After the view animation ends, the view may not be hidden and setVisibility(View.GONE) may fail. In this case, call view.clearAnimation() to clear the animation. This can fix such problems.

Summarize

The official account contains a systematic summary, but it is not very good to systematically learn a certain type of knowledge point;

So I wanted to write a booklet - the Gold Digging Booklet, so that friends can systematically learn a certain knowledge point;

<<:  WeChat and Alipay payment codes are restricted because of this group of people who launder money too aggressively

>>:  I studied Android JNI, but there are a few points I don't understand

Recommend

Will space junk hinder humanity's journey to the stars and the sea?

Key Points ★ If space junk grows like an avalanch...

World Economic Forum: Europe in the Age of AI

The World Economic Forum has released its report,...

We are classmates, so why is my deskmate so fragrant?

More and more people are beginning to believe tha...

iQIYI VIP price increases again, why?

iQiyi has raised its prices again. From 0:00 on D...

The weirdest, most disruptive, and coolest science/tech stories of 2015

[51CTO.com Quick Translation] With new achievemen...

Xiaohongshu Promotion Content Operation Strategy

I have to say that the speed of development of th...

APP operation and promotion: How to keep users and create value?

Through case studies, we explain in detail how to...

Bad example: Five steps to make your website slow down

Of course, we all want to provide a satisfying us...