[[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: - <?xml version= "1.0" encoding= "utf-8" ?>
- <animation-list
- xmlns:android= "http://schemas.android.com/apk/res/android"
- android:oneshot= "false" >
- <item android:drawable= "@drawable/refresh1" android:duration= "180" />
- <item android:drawable= "@drawable/refresh2" android:duration= "180" />
- ...
- <item android:drawable= "@drawable/refresh25" android:duration= "180" />
- </animation-list>
- view = findViewById(R.id.test);
- view .setBackgroundResource(R.drawable.drawable_test_anim);
- view .setOnClickListener(new View .OnClickListener() {
- @Override
- public void onClick( View v) {
- AnimationDrawable animationDrawable = (AnimationDrawable) view .getBackground();
- animationDrawable.start();
- }
- });
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; - <?xml version= "1.0" encoding= "utf-8" ?>
- < set xmlns:android= "http://schemas.android.com/apk/res/android"
- android:duration= "4000"
- android:fillAfter= "true"
- android:fillBefore= "true"
- android:interpolator= "@[package:]anim/interpolator_resource"
- android:repeatMode= "restart | reverse"
- android:repeatCount = "0"
- android:shareInterpolator= "true"
- android:startOffset= "float" >
- <alpha
- android:fromAlpha= "float"
- android:toAlpha= "float" />
- <scale
- android:fromXScale= "float"
- android:fromYScale= "float"
- android:pivotX= "float"
- android:pivotY= "float"
- android:toXScale= "float"
- android:toYScale= "float" />
- <rotate
- android:fromDegrees= "float"
- android:pivotX= "float"
- android:pivotY= "float"
- android:toDegrees= "float" />
- <translate
- android:fromXDelta= "float"
- android:fromYDelta= "float"
- android:toXDelta= "float"
- android:toYDelta= "float" />
- </ 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 - TextView textDemo = findViewById(R.id.text_demo);
- Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_animation_test);
- 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 - AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 2.0f);
- textDemo.startAnimation(alphaAnimation);
Monitor animation - alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
- @Override
- public void onAnimationStart(Animation animation) {
- //Animation start callback
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- //Animation end callback
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- //Callback when animation repeats
- }
- });
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 - ObjectAnimator animator = ObjectAnimator
- .ofInt(textDemo, "backgroundColor" , 0XffFF0000, 0Xff0000FF)
- .setDuration(2000);
- animator.setRepeatMode(ValueAnimator.RESTART);
- animator.setRepeatCount(10);
- animator.start();
2. Animation Collection - AnimatorSet animatorSet = new AnimatorSet();
- ValueAnimator translationX = ObjectAnimator.ofFloat(textDemo, "translationX" , 200f);
- ValueAnimator animator = ObjectAnimator
- .ofInt(textDemo, "backgroundColor" , 0XffFF0000, 0Xff0000FF);
- animatorSet.playTogether(translationX,animator);
- 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; - //Interpolator interface
- public interface Interpolator extends TimeInterpolator{
- // There is only one method inside
- float getInterpolation( float input) {
- // Parameter description
- // The input value range is 0-1, and changes evenly with the animation progress (0% - 100%)
- // When the animation starts, the input value = 0; when the animation ends, the input = 1
- // The middle value increases evenly between 0 and 1 as the animation progresses (0% - 100%)
- ...// Interpolator calculation logic
- return xxx;
- // The returned value is the fraction value used by the estimator to continue calculating, which will be explained in detail below
- }
- // TimeInterpolator interface
- // Same as above
- public interface TimeInterpolator {
- float getInterpolation( float input);
- }
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; - public interface TypeEvaluator {
- public Object evaluate( float fraction, Object startValue, Object endValue) {
- // Parameter description
- // fraction: the return value of the interpolator getInterpolation()
- // startValue: the initial value of the animation
- // endValue: the end value of the animation
- ....//Calculation logic of the estimator
- return xxx;
- // Specific values assigned to animation properties
- // 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 - ValueAnimator valueAnimator = ValueAnimator.ofInt(1, 100);
- valueAnimator.setDuration(2000); // animation duration
- valueAnimator.setRepeatCount(0);//Number of repetitions
- valueAnimator.setRepeatMode(ValueAnimator.REVERSE);//Repeat mode,
- valueAnimator.setStartDelay(20); //Delay time before starting
- valueAnimator.setEvaluator(new IntEvaluator()); //Evaluator
- valueAnimator.setInterpolator(new LinearInterpolator()); //Interpolator
- valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- //Get the current animation attribute value, which is 1~100
- Integer animatedValue = ( Integer ) animation.getAnimatedValue();
- //Get the animation percentage
- float animatedFraction = animation.getAnimatedFraction();
- ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
- int width = layoutParams.width;
- int height = layoutParams.height;
- layoutParams.height = height + 1;
- layoutParams.width=width+1;
- Log.e(TAG, "animatedValue: " +animatedValue+ " animatedFraction : " +animatedFraction
- + " width : " +layoutParams.width+ " height : " +layoutParams.height);
- textView.requestLayout();
- }
- });
- valueAnimator.start();
- }
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; |