In Android, animation has always been a good means of interaction, in the usual project development, often use some animation interaction, each time holding a GIF ran to say, can this animation be realized? Every time I say yes. However, for me this kind of Android white, it is really a little difficult, so there is some understanding of Android animation today, I hope to help you!!

This article focuses on the following aspects:

  • Android animation category:
  • Use of view animation:
  • Use of frame animation:
  • Use of property animation:

1. Android animation classification:

Android animation can be divided into:

  • Displacement of the animation
    • Translation TranslateAnimation
    • Rotating RotateAnimation
    • Zoom ScaleAnimation
    • Transparency AlphaAnimation
  • The frame of animation
  • Attribute animation

2. Use of view animation

First of all, I really don’t know if it’s my name, there are all kinds of names on the Internet, so let’s call it that first! Tube he? If only you knew what it was! All View animations that change the View position change the display position, not the actual position. Here are some common attributes used in View animations.

  • Android :duration Animation execution time
  • Android: Whether the View stays in the end position after fillAfter animation ends
  • Android :interpolator Defaults to (interpolator for acceleration or interpolator)
  • Android: whether shareInterpolator Shared interpolator

An image lets you understand that the position of the view animation actually hasn’t changed!

Here is a strong point, is the animation store location, I always confused at the beginning of the specific store location, in fact, still confused!! The anim folder must be created under res: res/anim/ xxx.xml, and the internal tags must be set tags!! If your new project doesn’t have an anim folder, you need to create it yourself!

###2.1 TranslateAnimation

The effect of pan animation does not go to the end. Here’s a quick overview of the properties used!

  • FromXDelta represents the starting value of x, such as 0,0%p
  • FromYDelta represents the starting value of y, such as 100,100%p
  • ToXDelta indicates the end value of x
  • ToYDelta represents the end value of y

If you directly set the distance here, from the control of the original location of the distance calculated, if you set the percentage 0% and 100% are equivalent to the parent control, in fact, the location set is the control of the beginning of the location to calculate! Remember these two points can, the rest of the effect can see!

The XML Settings used above are:

<? xml version="1.0" encoding="utf-8"? > <! -- Pan animation display --> <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fillAfter="true">

    <translate
        android:fromXDelta="0"
        android:toXDelta="100%" />
</set>
Copy the code

In fact, I only set the displacement of the X axis here. If you are interested, you can set the distance of the Y axis to see the effect! Of course, the above code can also be set by code! Like this…

TranslateAnimation = new TranslateAnimation(0,1000,0,0); translateAnimation.setDuration(500); translateAnimation.setFillAfter(true);
    mIvIcon.startAnimation(translateAnimation);
Copy the code

2.2 Rotation Animation

“Spin jump, I close my eyes” is the effect, as long as you pay attention to the rotation of the center of the animation can be determined. Take a look at common attributes first!!

  • Android :fromDegrees Start Angle of rotation
  • Android :toDegrees end rotation Angle
  • Android :pivotX Pivots on the X axis
  • Android :pivotY pivots on the Y-axis

The XML Settings used above are:

<? xml version="1.0" encoding="utf-8"? > <! -- Pan animation display --> <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fillAfter="true">

    <rotate
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360" />
</set>
Copy the code

The above effect code is set to:

    RotateAnimation rotateAnimation = new RotateAnimation(0, 360, mIvIcon.getWidth() / 2, mIvIcon.getHeight() / 2);
    rotateAnimation.setDuration(1000);
    mIvIcon.startAnimation(rotateAnimation);
Copy the code

2.3 Scaled Animation

The determination of the zoom position of the zoom animation is a crucial point for the entire animation, if you choose the wrong position, then the effect will be very poor, so the selection of the position is the most important!! Let’s start with the corresponding properties

  • Android :fromXScale x horizontal scaling start value, such as :0
  • Android :fromYScale y horizontal scaling start value, such as :0
  • Android :toXScale X vertical scaling start value
  • Android :toYScale y Start value of vertical scaling
  • Android: X coordinate of the toXScale axis point
  • Android :toYScale Specifies the Y coordinate of the scale point

The XML Settings used above are:

<? xml version="1.0" encoding="utf-8"? > <! -- Pan animation display --> <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fillAfter="true">

    <scale
        android:fromXScale="100%"
        android:fromYScale="100%"
        android:pivotX="0"
        android:pivotY="0"
        android:toXScale="50%"
        android:toYScale="50%" />
</set>
Copy the code

The above effect code is set to:

    ScaleAnimation scaleAnimation = new ScaleAnimation(mIvIcon.getWidth(), mIvIcon.getWidth() / 2, mIvIcon.getHeight(), mIvIcon.getHeight() / 2, 0, 0);
    scaleAnimation.setDuration(1000);
    mIvIcon.startAnimation(scaleAnimation);
Copy the code

Here in fact you know only one thing, zoom point and zoom distance, as long as the calculation of this can be!

2.4 AlphaAnimation

This animation is easier to understand! Is the change of transparency only!! The attributes are as follows:

  • Android :fromAlpha opacity starting value
  • Android: End value of toAlpha transparency

The XML Settings used above are:

<? xml version="1.0" encoding="utf-8"? > <! -- Pan animation display --> <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fillAfter="true">

    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.5" />
</set>
Copy the code

The above effect code is set to:

    AlphaAnimation scaleAnimation = new AlphaAnimation(1, 0);
    scaleAnimation.setDuration(1000);
    mIvIcon.startAnimation(scaleAnimation);
Copy the code

The code for loading all the XML above is as follows:

    Animation translateAnimation = AnimationUtils.loadAnimation(this,R.anim.XXX);
    mIvAnimation.startAnimation(translateAnimation);
Copy the code

Of course, you can simply combine all of the above animations in one XML file, like this

<? xml version="1.0" encoding="utf-8"? > <! -- Pan animation display --> <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="5000"
    android:fillAfter="true">

    <translate
        android:fromXDelta="0"
        android:toXDelta="100%" />

    <rotate
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360" />

    <scale
        android:fromXScale="100%"
        android:fromYScale="100%"
        android:pivotX="0"
        android:pivotY="0"
        android:toXScale="50%"
        android:toYScale="50%" />

    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.5" />
</set>
Copy the code

Some people actually struggle with whether to animate a view in code or in XML, but I think it’s better to animate it in XML, because there’s a lot of reuse, if you’re writing it in code, unless you’re writing a utility class. This depends on your needs, do not tangle with this thing, just like it!

2.5 Setting Listeners

Some special needs, when the animation is completed to do some corresponding operations to do, all will monitor the animation of the execution of some states, such as: start, end, again! The corresponding listening methods are as follows:

animaton.setAnimationListener(new Animation.AnimationListener() {@override public void onAnimationStart(Animation Animation) {@override public void onAnimationStart(Animation Animation) } @override public void onAnimationRepeat(Animation Animation) { }});Copy the code

Basically the usual project on view animation can be used so much, if there is any summary is not in place, please advise a big god!!

2.6 Use cases in some projects

2.6.1 Using View Animation on ViewGroup

For that matter, it’s pretty impressive. How so? In fact, this animation effect is very good! First look at an implementation of the renderings!

The above image is a view animation with layoutAnimation. There is a corresponding concept of layoutAnimation! It is the operation of the entire ViewGroup animation (can be any ViewGroup control), can achieve a delay effect! Let’s start with the corresponding properties.

  • Android: Delay indicates the time delay of the animation. For example, if the time period of the entry animation of the child element is 300ms, then 0.5 means that each child element needs to delay 150ms to play the entry animation
  • Android :animationOrder indicates the order of animation elements. There are three order options: Normal,reverse, and random. Reverse indicates the reverse display. Random indicates random display
  • Android: Animation specifies the specific entry animation for the element

Here are some of the corresponding attribute tags. Here’s how to use it! It’s actually very simple when you create this animation using create like this

<? xml version="1.0" encoding="utf-8"? > <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
                 android:animation="@anim/translate_animation"// Set the animation style of the inner child View!! android:animationOrder="normal"
                 android:delay="0.5"/>
Copy the code

You can use this XML in any controls you want, like android:layoutAnimation=”@anim/item_layoutanimation”

You can also use code to set it up like this

Animation animation = AnimationUtils.loadAnimation(this, R.anim.XXX); LayoutAnimationController controller = new LayoutAnimationController(animation); Controller. SetDelay (0.5 f); controller.setOrder(LayoutAnimationController.ORDER_NORMAL); View.setLayoutAnimation(controller); View.startAnimation(animation); // This sentence is used to start animationCopy the code

Note that XXX represents normal animation, not layoutAnimation. Animation XML make no mistake! This reminds me of the corresponding animation I used when WRITING MD. It feels like this! Hee hee…

  • The animation of the Activity switch

I’ve talked about this before in MD’s article, so I won’t say it here! If you are interested in MaterialDesign, see the MaterialDesign series (3). The realization of transition animation is not clear here! Haha, I find I’m really lazy, don’t I?

3. Use of frame animation:

In terms of the use of frame animation, it’s pretty much the same, the artist throws in a set of images and you set them up. Finally show it is ok, basically the process is the same! However, the disadvantage of frame animation is that it is easy to OOM when you use too many images. Therefore, it is recommended to use frame animation when animation is not much, otherwise it is not recommended to use!! The general flow of using frame animation is like this!

Common attributes:

  • Android :oneshot=”false” false infinite loop

Instructions:

  • Create the corresponding frame animation file :(pay attention! Drawable, not anim, is the location of this file.
<? xml version="1.0" encoding="utf-8"? > <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">

    <item
        android:drawable="@mipmap/icon1"
        android:duration="500"/>
    <item
        android:drawable="@mipmap/icon2"
        android:duration="500"/>
    <item
        android:drawable="@mipmap/icon3"
        android:duration="500"/>
    <item
        android:drawable="@mipmap/icon4"
        android:duration="500"/>
    <item
        android:drawable="@mipmap/icon5"
        android:duration="500"/>
    <item
        android:drawable="@mipmap/icon6"
        android:duration="500"/>
</animation-list>
Copy the code
  • Load the corresponding animation
imageView.setBackgroundResource(R.drawable.animation_list);
AnimationDrawable drawable = (AnimationDrawable)view.getBackground();
drawable.start();
Copy the code

4. Use of property animation

Property animation is referenced in Android3.0, as opposed to view animation. You can change the position of the control! Internal implementation is by changing the control’s property value to function! For this reason, you can change the size and position of the View. In fact, the content of the property animation includes:

  • ValueAnimator
  • ObjectAnimator inheritance ValueAnimator
  • TimeAnimator inheritance ValueAnimator
  • AnimatorSet A collection of animations
  • XML Settings for property animation
  • Problems encountered

Let’s take it one at a time! ValueAnimator this is a 3.0 property animation parent class, provides some common methods, for subclass implementation! So I’m going to skip that and go straight to the corresponding subclasses, the so-called descendents, and subclasses get it! The parent class will understand!

4.1 Using ValueAnimator

You said this is an animation! In fact, it is not, he just changes the corresponding attributes! Since it is a parent class, there is nothing to explain, but it has a common scenario that dynamically changes some properties of an object! Like this!!

ValueAnimator animator. = ValueAnimator ofInt (0400); animator.setDuration(1000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int curValue = (int)animation.getAnimatedValue(); // Here you can dynamically change some properties}}); animator.start();Copy the code

4.2 Using ObjectAnimator

This class is awesome. It does this by changing the corresponding properties, so the question is, what are the properties? When I first came into contact with this animation, it was called a property animation, but how do I know exactly what the properties are? Later I learned that any property with get/set method can be set, first for you to come to the appetizer!! Take a look at this effect first!

    ValueAnimator colorAnim = ObjectAnimator.ofInt(mRvBg, "backgroundColor", 0xffff8080, 0xff8080ff); colorAnim.setDuration(3000); colorAnim.setEvaluator(new ArgbEvaluator()); / * setting valuations, * / colorAnim setInterpolator (new AccelerateDecelerateInterpolator ()); /* Set the interpolator */ colorim.setrepeatCount (valueAnimator.infinite); Colorim.setrepeatmode (valueanimator.reverse); colorim.setrepeatMode (ValueAnimator. Colorim.start (); colorim.start ();Copy the code

And this is what you do by changing the background. So how do I know what properties to set? You just need to understand the concept of properties. When you receive data in JSON, the parameters are properties! In case you don’t understand, here is a picture about it!

The commonly used API:

  • SetDuration Sets the duration
  • SetEvaluator Sets the estimator
    • IntEvaluator (for frame number attributes)
    • FloatEvaluator (for floating-point attributes)
    • ArgbEvaluator (for Color attribute)
  • SetInterpolator Sets interpolator
    • TimeInterpolator TimeInterpolator
    • LinearInterpolator (uniform animation)
    • AccelerateDecelerateInterpolator acceleration deceleration interpolation (animation among two slow fast)
    • Activity AteInterpolator (Animation gets slower and slower)
  • SetRepeatCount Sets the number of cycles
  • SetRepeatMode Setting mode

There are a lot of APIS that are not actually used, and I’m not too ashamed to tell you! Afraid of my own understanding is wrong, mislead everyone! Hee hee…

In fact, the property animation, as long as you remember that it changes the property is good, the change will actually show there (or actually change the position)! So there is no problem with view animation just changing the display! The most commonly used notation in a project is something like this!

    ObjectAnimator.ofFloat(mIvAnimation, "rotationX", 0, 360),// objectAnimator. ofFloat(mIvAnimation,"rotationY", 0, 180),// rotate the Y axis objectAnimator. ofFloat(mIvAnimation,"rotation", 0, -90),// rotate objectAnimator. ofFloat(mIvAnimation,"translationX", 0, 90),// X-axis move objectAnimator. ofFloat(mIvAnimation,"translationY", 0, 90),// move y to objectAnimator. ofFloat(mIvAnimation,"scaleX", 1, 1.5f),// objectAnimator. ofFloat(mIvAnimation,"scaleY", 1, 0.5f),//Y axis zooming objectAnimator. ofFloat(mIvAnimation,"alpha", 1, 0.25f, 1)// GradientCopy the code

Inside the quotation marks are the corresponding attribute value, directly write the attribute name! ObjectAnimator also has ofInt() API, which is different from ObjectAnimator. Some ofMultiFloat() apis allow you to manipulate multiple property values at the same time. It’s pretty much the same thing as above. The last parameter of ofFloat is passed in a mutable array, which means you can pass in an infinite number of parameters (if you want!!). .

There is still a problem with eavesdropping: about eavesdropping

Public static interface AnimatorListener {// Initialize some resources void onAnimationStart(Animator animation); Void onAnimationEnd(Animator animation); Void onAnimationCancel(Animator animation); void onAnimationCancel(Animator animation); Void onAnimationRepeat(Animator animation); }Copy the code

4.3 TimeAnimator use

This is according to the time to set some attributes, provides a simple callback mechanism, through TimeAnimator. TimeListener, notify you at each frame of animation. This animator has no timing, interpolation, or object value Settings. The callback listener accepts information for each frame of the animation, including the total elapsed time and elapsed time from the previous frame to the present. There are very few methods, just a listen and return you the total time and the current frame time! Specific monitoring is as follows:

    public static interface TimeListener {
        void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime);
    }
Copy the code

4.4 AnimatorSet Animation collection

Put together the animation collection you need to execute! You can also do it in a certain order!

    AnimatorSet set = new AnimatorSet();
    set.playTogether(
        ObjectAnimator.ofFloat(mIvAnimation, "rotationX", 0, 360),// objectAnimator. ofFloat(mIvAnimation,"rotationY", 0, 180),// rotate the Y axis objectAnimator. ofFloat(mIvAnimation,"rotation", 0, -90),// rotate objectAnimator. ofFloat(mIvAnimation,"translationX", 0, 90),// X-axis move objectAnimator. ofFloat(mIvAnimation,"translationY", 0, 90),// move y to objectAnimator. ofFloat(mIvAnimation,"scaleX", 1, 1.5f),// objectAnimator. ofFloat(mIvAnimation,"scaleY", 1, 0.5f),//Y axis zooming objectAnimator. ofFloat(mIvAnimation,"alpha", 1, 0.25f, 1)// gradient); set.setDuration(500).start();Copy the code

There’s nothing to say about the code, just look at how it’s written! PlayTogether () this one API! If you want to execute animations one by one, use a new API (playSequentially(Animator… Items)) will do! The code is not posted here!! There are also some methods in it, whether something is up or running! We can go and have a look!

4.5 XML Settings for property animation

All parameters of the animation attributes are well understood, can be defined in the XML ValueAnimation, ObjectAnimator and AnimatorSet, including AnimatorSet corresponding labels, ValueAnimator corresponding labels, ObjectAnimator corresponds to the tag, and the convention is to name the tag that you can use

  • The detailed attributes of the <Set> tag

    • Android: The ordering of the animation can be set to two parameters.
      • 1. Together indicates that all child animations are executed at the same time;
      • 2. Sequentially means that all subsequences are executed in sequence. The default is together
  • Detailed properties of the <objectAnimator> and <animator> tags

    • Android :propertyName indicates the propertyName of the object on which the property animation works
    • Android :duration Indicates the animation duration
    • Android :valueFrom represents the initial value of the property animation
    • Android :valueTo indicates the end value of an attribute
    • Android :startOffset indicates the delay time of the animation. Once the animation has started, how many milliseconds must be delayed before the animation can actually play
    • Android :repeatCount indicates the number of times the animation is repeated
    • Android :repeatMode indicates the animation repeatMode
    • android:valueType Indicates the type of property specified by Android:propertyName. The options are “intType” and “floatType”, representing integers and floatType respectively. If Android:propertyName specifies a colour, then andro is not required Id :valueType The system automatically performs attribute processing for the color type

Ps: Here’s an illustration:

  1. Android :repeatCount indicates the number of animation cycles. Default is 0. When -1, it indicates the wireless cycle
  2. Android :repeatMode refers to the reverse repetition of the animation cycle mode. When the first playback is completed, the animation will be played backwards for the second time, the animation will be played from the beginning for the third time, and the animation will be played backwards for the fourth time, so as to cycle

The XML instance

<? xml version="1.0" encoding="utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:ordering="together">

    <objectAnimator
        android:duration="300"
        android:propertyName="x"
        android:valueTo="200"
        android:valueType="intType"/>

    <objectAnimator
        android:duration="300"
        android:propertyName="y"
        android:valueTo="200"
        android:valueType="intType"/>
</set>
Copy the code

Use in code

    AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.animator_anim);
    set.setTarget(mIvAnimation);
    set.start();
Copy the code

It is highly recommended that you write in XML when using animation, because it is more reusable! Trust me, either you write a bunch of code every time you write an animation!

4.5 Problems encountered

Animates any object using properties.

  • There must be corresponding GET /set methods, otherwise an exception will be reported
  • The corresponding GET /set method should be visually reflected from the UI level, otherwise the effect will not be visible
  • It is also important to note that this property animation is applied to the View object, so it should be a property that the View has, not a property regenerated by the object that inherits it

For the inherited View to use the property animation situation, the official provides the corresponding solution:

  • Assign the corresponding get/set method to the object (if you have permission)
  • The original object is wrapped in a class that indirectly provides get/set methods
/** * author: He Jinlong * create time: 2017/10/29 14:21 * description: Wrapper class to provide the corresponding GET /setSince there is no corresponding method to change the width and height, there is a corresponding get/ package heresetPublic class ViewWrapper {private View mTargetView; /** * author: He Kinglong * create time: 2017/10/29 14:28 * description: Pass the corresponding View, set some contents * instructions: * version: */ public voidsetTargetView(View targetView) { mTargetView = targetView; } /** * author: He * create time: 2017/10/29 14:30 * description: Obtain the width of the method * Instructions: * version: */ public intgetWidth() {
           returnmTargetView.getLayoutParams().width; } /** * author: He Kinglong * create time: 2017/10/29 14:31 * description: set the width method * Instructions: set the corresponding width * version: * * @param width */ public voidsetWidth(int width) { mTargetView.getLayoutParams().width = width; / * redraw the View method * / mTargetView requestLayout (). }}Copy the code

Use in code

// Use code ViewWrapper wrapper = new ViewWrapper(); wrapper.setTargetView(view); ObjectAnimator.ofInt(wrapper,"width", 0, 500).setDuration(1000).start();
Copy the code

Pass in a View and set the width and height of the View through LayoutParams. This is equivalent to setting the width and height of the View


On the animation content of the development of the time summed up so much, there are many details did not explain, the article is also quite messy, I hope you do not mind, after all, I am not a liberal arts graduate! My Chinese score is not high either!! Sorry, if you don’t understand anything, you can leave me a message. What I see will fix it for you! Haha, that’s all for today! Bye-bye…