A brief introduction to animation and transition

Animation requirements are so common in Android development, but sometimes they get forgotten and you have to go back to the source.

When the interface changes in response to user actions, you should animate the layout changes. These animations provide feedback to the user about the action and help keep the user focused on the interface.

Animations are visual reminders that the application has changed. For those interested in studying animation Design specifications, check out the Material Design action guide


Figure 1.1 Clever animations for the appearance and disappearance of dialogs make interface changes less obtrusive

Starting with Android4.4 (API 19), Android provides a transitional framework for quickly animating activities or fragments that switch layouts. You only need to specify the starting and ending layout and the type of animation to use. The system then finds and executes the animation between the two layouts.

Note: In Android 5.0 (API 21) and later, the Android transition framework only supports animations that transition between activities


Figure 1.2 Interface transition effect (from Android official website)

Two attribute animation basics

Android animations fall into two broad categories:

  1. View the animation
  2. Attribute animation

There are two types of view animation:

  • Filling between animation
  • The frame of animation

View animation due to implementation problems, such as it will only be modified in the position of the drawing view, but not modify the actual view itself, etc., has gradually faded out of the field of vision, here is not too much explanation, you need to simply view the view animation introduction and animation resources or find information, welcome to add information links

2.1 Overview of attribute animation

Property animation is a very robust and flexible framework that allows you to define an animation of any property that changes over time, in short, updating the property to achieve the effect of the animation.

For example, in the case of the custom progress property, it only changes the assignment of the field, but does not automatically trigger the redraw mechanism. You need to declare invalidate() in the custom setProgress() method.

Property animation and advanced, you can directly view the throw line god’s article, knowledge details, but also with video explanation:

  • HenCoder Android Custom View 1-6: Properties animation
  • Customize View 1-7: Property animation (Advanced)
  • HenCoder Android custom View 1-8 Hardware acceleration

Animation knowledge is more, remember that there is such a thing, in the actual open, need to achieve, there is a general direction, come back to review again.

God’s article, the attribute animation is very thorough and comprehensive, you can directly view the god article. Here is just to do additional knowledge records and summary of the content, convenient for personal recall.

Most of the images in this article are from the Android website or the above three articles

2.2 Overview of properties animation features

In the attribute animation system, you can customize the following general characteristics of the animation:

  1. Animation duration: Specifies the animation duration. The default duration is 300ms
  2. Time interpolator/speed model: Specify how to calculate the value of the property based on the current playing time of the animation
  3. RepeatCount and repeatMode: Repeatnumber and repeatmodel, specifying whether and how many times the animation is repeated after the end of a certain period. You can also specify whether to play the animation backwards.
  4. Animation listener: Set up a listener for the animation, so that you can get feedback at critical moments, so that you can make appropriate actions in time, such as updating other data synchronously when the animation’s properties are updated, or recycling resources after the animation ends, etc.
  5. Using TypeEvaluator: Custom implements an animatable property type TypeEvaluator

2.3 Implementation method of attribute animation

The Android animation system provides three classes of Animator implementations:

category instructions
ValueAnimator Main timing engine for property animation. Animating a property consists of two steps: calculating the values after animating the property, and setting those values for the object and property to which the animating effect is to be applied.ValueAnimator Do not performThe second step, therefore, is that you must listen for updates to the values calculated by ValueAnimator and use your own logic to modify the object to which you want to animate. For details, please refer toAdd the animation effects section using ValueAnimator
ObjectAnimator A subclass of ValueAnimator that sets the target object and object properties to add animation effects. After calculating the new value of the animationUpdate accordinglyProperties. In most cases, you can use it because it greatly simplifies the process of animating the value of the target object. For details, please refer toAdd the animation effects section using ObjectAnimator
AnimatorSet This class provides a set mechanism for animation,Controls the execution order of multiple animations, you can set the animations to play together, in sequence, or after a specified delay. For details, please refer toOrchestrate multiple animation sections using animatorSets.
ViewPropertyAnimator Behavior and expressionObjectAnamtorVery similar, but much easier to use, more efficient and easier to read. For details, please refer toAdd animation effects using ViewPropertyAnimator.

ValuesAnimator is the core computing engine for animation, but its subclass ObjectAnimator is used because it is too basic. ViewPropertyAnimator is a convenient version of ObjectAnimator. Animatorsets are different in that they control the order in which multiple animations are executed. For more understanding, check out the basic wheel of ValueAnimator

In addition, ViewPropertyAnimator does not need to call the start() method, whereas other types do

2.4 General features: interpolator/speed model

Interpolator: Specifies how specific values in an animation are evaluated based on time. For example, you can specify that the animation plays in a linear fashion throughout the animation, that is, the animation moves uniformly throughout the playback; You can also specify that the animation uses non-linear time, such that the animation speeds up after it starts and slows down before it ends.

The specific Interpolator type and usage is described as follows: setInterpolator(Interpolator Interpolator) Sets Interpolator

If an existing interpolator type does not work, you can implement your own interpolator by implementing the TimeInterpolator interface.

2.5 Common Features: Listeners

2.5.1 Listener Types

(1)Animator.AnimatorListener

  • onAnimationStart()– Called when the animation starts playing.
  • OnAnimationEnd () – called when the animation ends and plays.

  • OnAnimationRepeat () – called when the animation is repeated.

  • OnAnimationCancel () – called when the animation is cancelled.

    Note: Cancelled animations are also calledonAnimationEnd()No matter how they end.

(2)ValueAnimator.AnimatorUpdateListener

  • onAnimationUpdate()– Call each frame of the animation. Listen for this event to useValueAnimatorComputed values generated during animation playback. To use this value, the query is passed into the eventValueAnimatorObject to usegetAnimatedValue()Method gets the value after the animation effect is currently added. If you useValueAnimator, this listener must be implemented.

(3)Animator.AnimatorPauseListener

  • onAnimationPause(Animator animation)– Called when the animation is paused.
  • onAnimationResume(Animator animation)– Called when the animation resumes.

Note: if you don’t need to implement Animator. AnimatorListener interface all the methods, you can extend AnimatorListenerAdapter class, instead of implementing an interface. AnimatorListenerAdapter class inherits the Animator. AnimatorPauseListener and Animator. AnimatorListener interface, and provides an empty implementation. You can rewrite the corresponding method as required.

2.5.2 Setting Listeners

ViewPropertyAnimator and ObjectAnimator are slightly different: ViewPropertyAnimator uses the setListener() and setUpdateListener() methods to set a listener, To remove listeners, set[Update]Listener(null) is filled with a null value. ObjectAnimator adds one or more listeners with addListener() and addUpdateListener(), and removes listeners by removing [Update]Listener().

The other differences are:

  1. Due to theObjectAnimatorSupport the use ofpause()Methods suspensionSo it has one moreaddPauseListener() / removePauseListener()Support;
  2. ViewPropertyAnimator has its own withStartAction() and withEndAction() methods, which can set up a one-time start or end of the animation listening.

For ViewPropertyAnimator. WithStartAction/EndAction (), and the Animator. AnimatorListener onAnimationStart ()/onAnimationEnd () There are two major differences:

  1. WithStartAction ()/withEndAction() are disposable and are automatically deprecated after the animation is executed, and the callbacks set with them will not be called even if the ViewPropertyAnimator is reused for another animation. The AnimatorListener set by set/addListener() is always in effect, and the callback will always be called when the animation is repeated.

  2. The callback set by withEndAction() is only called when the animation ends normally, and not executed when the animation is canceled. This and AnimatorListener onAnimationEnd () behavior is not consistent.

Three properties animation advanced chapter

3.1 Animating properties for specific properties: TypeEvaluator

If you want to animate a type that is not recognized by the Android system, you can create your own identification by implementing the TypeEvaluator interface. The Android system itself recognizes types like int, float, or color, and is actually supported by the IntEvaluator, FloatEvaluator, and ArgbEvaluator classes, respectively.

For an implementation, see custom Evaluator

img

Color attribute animation

3.2 Changing multiple properties in the same animation: PropertyValuesHolder

PropertyValuesHolder Changes multiple properties in the same animation

Many times, you will need to change multiple properties in the same animation, such as changing the size while changing the transparency. If you use ViewPropertyAnimator, you can change multiple properties in an animation directly by concatenating them:

view.animate()

        .scaleX(1)

        .scaleY(1)

        .alpha(1)

Copy the code
img

This is not the case with ObjectAnimator. However, you can use PropertyValuesHolder to change multiple properties simultaneously in one animation.

PropertyValuesHolder holder1 = PropertyValuesHolder.ofFloat("scaleX".1);

PropertyValuesHolder holder2 = PropertyValuesHolder.ofFloat("scaleY".1);

PropertyValuesHolder holder3 = PropertyValuesHolder.ofFloat("alpha".1);



ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(view, holder1, holder2, holder3)

animator.start();

Copy the code

PropertyValuesHolder, as the name suggests, is a batch store of property values. So if you have multiple properties that need to be modified, you can put them in different PropertyValuesHolder and then use ofPropertyValuesHolder() to put them in the Animator. This way you don’t have to create a separate Animator for each property to execute separately.

3.3 Execution of multiple animations: AnimatorSet

AnimatorSet Multiple animations executed together

As mentioned earlier, an AnimatorSet is a class that controls the execution of multiple animations, such as moving content from 0 to 100% size. This is not the case using PropertyValuesHolder, because these properties, if placed in the same animation, will share a series of Settings such as start time, end time, Interpolator, etc., so that the animation will not be executed sequently.

That’s where the AnimatorSet comes in.

ObjectAnimator animator1 = ObjectAnimator.ofFloat(...) ;

animator1.setInterpolator(new LinearInterpolator());

ObjectAnimator animator2 = ObjectAnimator.ofInt(...) ;

animator2.setInterpolator(new DecelerateInterpolator());



AnimatorSet animatorSet = new AnimatorSet();

// The two animations are executed in sequence

animatorSet.playSequentially(animator1, animator2);

animatorSet.start();

Copy the code
img

With playSequentially(), you can play the two animations sequentially without having to set up listeners for them to manually monitor their collaboration.

AnimatorSet can also be used like this:

// Both animations are executed simultaneously

animatorSet.playTogether(animator1, animator2);

animatorSet.start();

Copy the code

And use it this way:

/ / use AnimatorSet. Play (animatorA) with/before/after (animatorB)

// to precisely configure the relationships between animators

animatorSet.play(animator1).with(animator2);

animatorSet.play(animator1).before(animator2);

animatorSet.play(animator1).after(animator2);

animatorSet.start();

Copy the code

With AnimatorSet, you can plan and manage multiple animators uniformly and make them work in the desired order.

3.4 split the same attributes: PropertyValuesHolders ofKeyframe ()

The following content from: PropertyValuesHolders ofKeyframe split () the same attribute

In addition to merging multiple properties and blending multiple animations, you can go one step further with PropertyValuesHolder and split the same animation property into multiple stages by setting keyFrames. For example, you can increase a progress to 100% and then “bounce” back.

// Start at 0%

Keyframe keyframe1 = Keyframe.ofFloat(0.0);

// The animation is 100% complete after 50% of the time

Keyframe keyframe2 = Keyframe.ofFloat(0.5 f.100);

// When the time is 100%, the animation's completion regress to 80%, i.e., it bounces 20%

Keyframe keyframe3 = Keyframe.ofFloat(1.80);

PropertyValuesHolder holder = PropertyValuesHolder.ofKeyframe("progress", keyframe1, keyframe2, keyframe3);



ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(view, holder);

animator.start();

Copy the code
img

Declare attribute animation through XML

4.1 Declare animations in XML

The property animation system supports the use of XML to declare property animations. By defining animations in XML, you can easily reuse animations in multiple activities and easily change the order in which they are executed.

To distinguish it from the animation files of the older view animation framework, starting with Android 3.1, you should save the XML file for the property animation in the res/animator/ directory

Property animation type, corresponding to the following XML tag:

  • ValueAnimator<animator>
  • ObjectAnimator<objectAnimator>
  • AnimatorSet<set>

To find the details of attributes that can be used in XML declarations, consult the animation resources

In the following example, opacity is set to 1 and two sets of object animations are played in sequence, with the first nested set playing two object animations simultaneously:

 <set android:ordering="sequentially">

      <objectAnimator

            android:valueFrom="0.0"

            android:valueTo="1.0"

            android:propertyName="alpha"

            android:duration="0" />


        <set>

            <objectAnimator

                android:propertyName="x"

                android:duration="500"

                android:valueTo="400"

                android:valueType="intType"/>


            <objectAnimator

                android:propertyName="y"

                android:duration="500"

                android:valueTo="300"

                android:valueType="intType"/>


        </set>

        <objectAnimator

            android:propertyName="alpha"

            android:duration="500"

            android:valueTo="1f"/>


    </set>

Copy the code

To load an animation into a view, you need to load the XML resource as an AnimatorSet object, then call setTarget() to set the target object, and call start().

  (AnimatorInflater.loadAnimator(myContext, R.animator.property_animator) as AnimatorSet).apply {

        setTarget(myObject)

        start()

    }

Copy the code

ValueAnimator can also be declared in XML:

 <animator xmlns:android="http://schemas.android.com/apk/res/android"

        android:duration="1000"

        android:valueType="floatType"

        android:valueFrom="0f"

        android:valueTo="-100f" />


Copy the code

ValueAnimator, then add an AnimatorUpdateListener, get the updated animator value, and use it in a view property as ValueAnimator does:

 (AnimatorInflater.loadAnimator(this, R.animator.animator) as ValueAnimator).apply {

        addUpdateListener { updatedAnimation ->

            textView.translationX = updatedAnimation.animatedValue as Float

        }



        start()

    }

    

Copy the code

4.2 the use ofStateListAnimatorAdd animation effects for view state changes

Like the Drawable resource root

, the Android animation system provides a StateListAnimator, which you can define to run when the view state changes. Such as when the view is pressed to enlarge, release when the original state.

The file needs to be stored in the res/ XML/directory, again wrapped with a root

element, and defined with a child

element to define the state. Create a state Animator, press to enlarge the x/Y ratio of the view, release to restore the state:

    
      

    <selector xmlns:android="http://schemas.android.com/apk/res/android">

        <! -- the pressed state; increase x and y size to 150% -->

        <item android:state_pressed="true">

            <set>

                <objectAnimator android:propertyName="scaleX"

                    android:duration="@android:integer/config_shortAnimTime"

                    android:valueTo="1.5"

                    android:valueType="floatType"/>


                <objectAnimator android:propertyName="scaleY"

                    android:duration="@android:integer/config_shortAnimTime"

                    android:valueTo="1.5"

                    android:valueType="floatType"/>


            </set>

        </item>

        <! -- the default, non-pressed state; set x and y size to 100% -->

        <item android:state_pressed="false">

            <set>

                <objectAnimator android:propertyName="scaleX"

                    android:duration="@android:integer/config_shortAnimTime"

                    android:valueTo="1"

                    android:valueType="floatType"/>


                <objectAnimator android:propertyName="scaleY"

                    android:duration="@android:integer/config_shortAnimTime"

                    android:valueTo="1"

                    android:valueType="floatType"/>


            </set>

        </item>

    </selector>

Copy the code

Apply StateListAnimator to view, you need to add * * android: StateListAnimator * * attributes:

 <Button android:stateListAnimator="@xml/animate_scale"

            . />


Copy the code

If you want to assign StateListAnimator through code view, can use AnimatorInflater. LoadStateListAnimator () method, Then use the setStateListAnimator () method will be assigned to the View Animator

5 Reference Links

  1. Animations and Transitions

  2. HenCoder Android Custom View 1-6: Properties animation

  3. Customize View 1-7: Property animation (Advanced)

  4. HenCoder Android custom View 1-8 Hardware acceleration

Thank you. ❤ ️

  1. If you find this post helpful, give it a thumbs up (👍).

  2. About error correction and suggestions: Welcome to share the record directly in the message (🌹)

– END –