I usually project development necessary framework
- The strongest network request Net on Android
- The strongest list on Android (including StateLayout) BRV
- Android’s strongest default page StateLayout
- JSON and long text log printing tool LogCat
- Supports asynchronous and global customization of the toast tool Tooltip
- Develop the debugging window tool DebugKit
- One line of code creates the transparent StatusBar StatusBar
Classification of animation
Main categories:
- View Animation
- Drawable Animation
- Property Animation
Traditional animation
Traditional animation refers to the animation implementation before android3.0. Only the interface changes, but the position properties (that is, the screen coordinates) do not.
The key class
-
Animation. AnimationListener Animation event listeners
-
Interpolator Animation Interpolator
-
Animation Abstract class of an Animation
-
AnimationUtils Animation utility class
-
AnimationDrawable frame animation
Animations support both Java code and XML layout to create animation effects.
The Java class name | XML keyword | Description information |
---|---|---|
AlphaAnimation | <alpha> Place it in the res/anim/ directory |
Gradient transparency animation effect |
RotateAnimation | <rotate> Place it in the res/anim/ directory |
Screen transfer rotation animation effect |
ScaleAnimation | <scale> Place it in the res/anim/ directory |
Tween size scaling animation effect |
TranslateAnimation | <translate> Place it in the res/anim/ directory |
Screen shift position move animation effect |
AnimationSet | <set> Place it in the res/anim/ directory |
A container that holds other animation elements alpha, scale, Translate, rotate, or other set elements |
Animation
Animation is the abstract base class for all traditional animations; So here are the general properties and methods for all animations
attribute | methods | describe |
---|---|---|
android:detachWallpaper | setDetachWallpaper(boolean) | Whether to allow running on wallpaper |
android:duration | setDuration(long) | Animation duration in milliseconds |
android:fillAfter | setFillAfter(boolean) | Control whether the last state of the animation remains when the animation ends |
android:fillBefore | setFillBefore(boolean) | Control whether the animation ends in the state before the animation began |
android:fillEnabled | setFillEnabled(boolean) | The same effect as Android :fillBefore |
android:interpolator | setInterpolator(Interpolator) | Set interpolators (specify animation effects, such as rebound, etc.) |
android:repeatCount | setRepeatCount(int) | Number of repetitions, if 1, the animation is executed twice |
android:repeatMode | setRepeatMode(int) | Repetitive patterns |
android:startOffset | setStartOffset(long) | The time, in milliseconds, to wait to start running after calling the start function |
android:zAdjustment | setZAdjustment(int) | Represents the position on the Z-axis (top/bottom/normal) where the content is animated when it runs. The default is normal |
Does pay attention to
- Class names are different from tag names in XML
- After is valid if FillAfter and FillBefore are both true. The default is Before
There is no corresponding Animation function
void start (a)
// Start animation (only on getTransition)
void cancel (a)
// End the animation (if the animation is currently executing)
void reset (a)
// If an animation is finished and you want to start the animation again
void setBackgroundColor (int bg)
void setInterpolator (Context context,
int resID)
Interpolator file in resource
Copy the code
Sets the listener for the animation event
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// Start animation
}
@Override
public void onAnimationEnd(Animation animation) {
// End of animation
}
@Override
public void onAnimationRepeat(Animation animation) {
// The animation repeats. If the setRepeat method is executed, it will be called back every time the animation is loaded}});Copy the code
View
About setting the View’s animation function
void setAnimation (Animation animation)
// Animation set by this function will not be executed until the parent container calls inviliData()
void startAnimation (Animation animation)
// Set up the animation and execute it immediately
void clearAnimation (a)
Animation getAnimation (a)
void postInvalidateOnAnimation (int left,
int top,
int right,
int bottom)
void postInvalidateOnAnimation (a)
void postOnAnimation (Runnable action)
void postOnAnimationDelayed (Runnable action,
long delayMillis)
Copy the code
View’s built-in animation life cycle
void onAnimationStart ()
void onAnimationEnd ()
Copy the code
AlphaAnimation
Set the transparent animation effect
XML attributes | explain |
---|---|
android:fromAlpha | The percentage of transparency at the beginning of the animation (0.0 to 1.0, 0.0 being fully transparent, 1.0 being opaque) |
android:toAlpha | Opacity at the end of the animation, ditto |
The constructor creates the animation
AlphaAnimation (float fromAlpha,
float toAlpha)
AlphaAnimation (Context context,
AttributeSet attrs)
Copy the code
Loading an XML animation
Animation animation = AnimationUtils.loadAnimation(this, R.anim.animation_set);
mButton.startAnimation(animation);
Copy the code
RotateAnimation
Set the rotation animation effect
XML attributes | explain |
---|---|
android:fromDegrees | Rotation Angle, positive represents clockwise degrees, negative represents counterclockwise degrees |
android:toDegrees | Rotation end Angle, positive represents clockwise degrees, negative represents counterclockwise degrees |
android:pivotX | Scale the starting X coordinate |
android:pivotY | Scale the starting Y coordinate, same as above |
Note that Pivot supports three property values, and there are other animations that support these values as well. Look backward
-
50
Represents a point 50 pixels wide or high from the upper left corner of the View
-
50%
Represents a pixel starting from the upper left corner of the View offset by 50% of the width or height of the View itself
-
50%p
Represents a pixel starting from the upper left corner of the View offset by 50% of the width or height of the View’s parent container
You can also use constructors directly in code creation
RotateAnimation (Context context,
AttributeSet attrs)
RotateAnimation (float fromDegrees,
float toDegrees)
RotateAnimation (float fromDegrees,
float toDegrees,
float pivotX,
float pivotY)
RotateAnimation (float fromDegrees,
float toDegrees,
int pivotXType, // This parameter is used to implement the three values in the XML attribute
float pivotXValue,
int pivotYType,
float pivotYValue)
Copy the code
About pivotType value
- Animation.relative_to_self is equivalent to 50% of XML
- Animation.relative_to_parent is equivalent to 50% P of XML
- Animation.ABSOLUTE equals 50
TranslateAnimation
Set the pan animation effect
Properties:
Corresponding to the start coordinate and end coordinate of translation respectively, also supporting three attribute values.
A constructor
TranslateAnimation (Context context,
AttributeSet attrs)
TranslateAnimation (float fromXDelta,
float toXDelta,
float fromYDelta,
float toYDelta)
TranslateAnimation (int fromXType,
float fromXValue,
int toXType,
float toXValue,
int fromYType,
float fromYValue,
int toYType,
float toYValue)
Copy the code
About Type (similar to RotateAnimation):
- Animation.relative_to_self is equivalent to 50% of XML
- Animation.relative_to_parent is equivalent to 50% P of XML
- Animation.ABSOLUTE equals 50
ScaleAnimation
Set the zoom animation effect
Properties:
Corresponding:
- Scaling starting point
- Scale center coordinates
- Scaling terminal coordinates
- Floating point setting percentages are not supported in XML (except alpha)
- Animation property code completion is not supported in XML
- ScaleAnimation supports DP values in XML
- Set percentages in code to all be expressed as floating point numbers (1 means 100%)
AnimationSet
Multiple animation effects can be set to play simultaneously
<? The XML version = "1.0" encoding = "utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500"> <translate android:duration="2000" android:fromXDelta="0" android:fromYDelta="0" android:repeatCount="-1" android:toXDelta="100" android:toYDelta="100" > </translate> <scale android:duration="2000" android:fromXScale="0" android:fromYScale="0" android:repeatCount="-1" android:toXScale="1" android:toYScale="1" > </scale> <rotate android:duration="2000" android:fromDegrees="0" android:pivotX="0" android:pivotY="100" android:repeatCount="-1" android:toDegrees="360" > </rotate> <alpha android:duration="2000" android:fromAlpha="1" android:repeatCount="-1" android:toAlpha="0" > </alpha> </set>Copy the code
The code sets the animation collection
Animation animation = AnimationUtils.loadAnimation(this, R.anim.animation_set);
mButton.startAnimation(animation);
Copy the code
Note that AnimationSet does not support repeatCount properties (i.e., no direct support for looping animations). However, you can add a separate loop to the animation using the above method (the code can also be set to repeat);
Tip: The view animation set only supports multiple animations simultaneously. No support for chaining animation (unless you listen for animation)
Add animations through functions
void addAnimation (Animation a)
Copy the code
AnimationUtils
This class has been used previously to load XML animations. Now I’m going to focus on
The main role
- Load the XML animator/interpolator
- Provides several animation effects
It is then set to play on the View with view.startAnimation ()
// The elapsed time of the current animation, in milliseconds
long currentAnimationTimeMillis (a)
// Load the animation
Animation loadAnimation (Context context,
int id)
// Load the interpolator
Interpolator loadInterpolator (Context context,
int id)
// Load the layout animation
LayoutAnimationController loadLayoutAnimation (Context context,
int id)
Copy the code
Generate native animation effects (up, down, left, and right/move out of animation)
// Generates an animation that slides and fades from left to original coordinates
Animation makeInAnimation (Context c,
boolean fromLeft) // Whether to enter from the left, otherwise enter from the right
// Generates a sliding fade animation from bottom to top
Animation makeInChildBottomAnimation (Context c)
// Generates a fade animation and moves left/right out of the interface
Animation makeOutAnimation (Context c,
boolean toRight)
Copy the code
The frame of animation
Frame animation is loading a Drawable resource to play the animation, like Gif images loading multiple consecutive images frame by frame to create the animation effect. Due to the need to load multiple pictures are generally large in volume and easy to affect the smoothness, but it is very convenient to make the effect can be very complicated. Note The OOM memory overflows.
A frame: just a Drawable
The corresponding class of frame animation is AnimationDrawable, which is a subclass of Drawable, so it can be used as the BackgroundDrawable of View.
The sample
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mAnimationDrawable = new AnimationDrawable(); // Create an animation
// Add a frame image
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_20_black_24dp), 200);
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_30_black_24dp), 200);
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_50_black_24dp), 200);
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_60_black_24dp), 200);
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_80_black_24dp), 200);
mAnimationDrawable.addFrame(getDrawable(R.drawable.ic_battery_90_black_24dp), 200);
// Set the animation object to the imageView object as the background, you can also set the background in the layout file
mIvFrame.setBackground(mAnimationDrawable);
}
@OnClick({R.id.btn_start_animation, R.id.btn_stop_animation})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_start_animation:
mAnimationDrawable.start(); // Start animation
break;
case R.id.btn_stop_animation:
mAnimationDrawable.stop(); // Stop the animation, this method will automatically determine whether the animation is running
break; }}Copy the code
In addition to creating in code, you can also create an XML file in the Drawable directory. Use the node animation-list.
<?xml version="1.0" encoding="utf-8"? >
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_battery_20_black_24dp" android:duration="200"/>
<item android:drawable="@drawable/ic_battery_30_black_24dp" android:duration="200"/>
<item android:drawable="@drawable/ic_battery_50_black_24dp" android:duration="200"/>
<item android:drawable="@drawable/ic_battery_60_black_24dp" android:duration="200"/>
<item android:drawable="@drawable/ic_battery_80_black_24dp" android:duration="200"/>
<item android:drawable="@drawable/ic_battery_90_black_24dp" android:duration="200"/>
</animation-list>
Copy the code
Once created with XML, you still need to display the animation in your code.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// AnimationDrawable is a subclass of Drawable, which can be thought of as an image. Just like giFs are made up of multiple images
mAnimationList = (AnimationDrawable) getDrawable(R.drawable.animation_frame);
mIvFrame.setBackground(mAnimationList); // Set the animation as the background again
// mIvFrame.setImageDrawable(mAnimationDrawable); It's not just the background, of course
}
@OnClick({R.id.btn_start_animation, R.id.btn_stop_animation})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_start_animation:
mAnimationList.start();
break;
case R.id.btn_stop_animation:
mAnimationList.stop();
break; }}Copy the code
AnimationDrawable
Add the frame
void addFrame Drawable frame, // Drawable frameint duration) // The duration of a frame in milliseconds
Copy the code
Get duration
int getDuration (int i)
Copy the code
Get a frame image
Drawable getFrame (int index) // Get the Drawable object with the specified index in the frame-by-frame animation, starting at 0
Copy the code
I get the total number of frames
int getNumberOfFrames (a) // How many frames do you set for a frame by frame animation
Copy the code
Fill in the XML
This method populates the object with an XML file. Added in Android5.0(API21), rarely used. And it’s even better to set the XML directly as the background. Several parameters involved in custom properties will be covered in a separate article.
void inflate (Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
Copy the code
Execution duration
void setOneShot (boolean oneShot) // Sets whether to play once. The default value is false
boolean isOneShot (a) // Whether to play once
Copy the code
Whether an animation is playing
boolean isRunning (a)
Copy the code
Start and Stop
void start (a) // It's officially not recommended to execute within the Activity's onCreate(), but I've had no problems executing it
void stop (a)
void run (a) // You can also start animation, but the official recommendation is start()
Copy the code
Restart and pause the animation
Although the name is show and hide, animation hiding is similar to suspending animation, after all, the frame animation attached to the View will still show a frame on the screen. So I think it’s more like a pause animation.
boolean setVisible (booleanVisible, // Whether to show or hideboolean restart) // Whether to restart the animation
Copy the code
Note that a restart setting of true or going from hide to show will cause the frame-by-frame animation to restart. So it doesn’t work either.
Boolean return value: true if the current state is different from the previous state, false anyway. For example: false from show to hide, false from restart.
interpolator
Interpolator Animation Interpolator is used to control the speed change of an animation.
Property animation and view animation are compatible with the same animation interpolator.
Key categories:
TypeEvaluator
All interpolators have one top-level interface: Interpolator
class | xml | describe |
---|---|---|
AccelerateDecelerateInterpolator | @android:anim/accelerate_decelerate_interpolator | The animation starts and ends at a slower rate and speeds up in the middle |
AccelerateInterpolator | @android:anim/accelerate_interpolator | The animation starts slowly and then speeds up |
AnticipateInterpolator | @android:anim/anticipate_interpolator | Similar to slingshot, first pull back and then move to the specified coordinates; |
AnticipateOvershootInterpolator | @android:anim/anticipate_overshoot_interpolator | Similar to the above, but with a damping effect when pulled backwards; |
BounceInterpolator | @android:anim/bounce_interpolator | When reaching the specified value, there will be a pop-up effect; |
CycleInterpolator | @android:anim/cycle_interpolator | It goes to the specified position and then it goes back to the same value and then it goes back to the original value; |
DecelerateInterpolator | @android:anim/decelerate_interpolator | The animation starts fast and then slow |
LinearInterpolator | @android:anim/linear_interpolator | The animation changes at constant speed |
OvershootInterpolator | @android:anim/overshoot_interpolator | Pop a certain value forward and return to the original position |
PathInterpolator | The path | New, run according to path coordinates after defining path coordinates. |
Interpolator three interpolators are added after android5.0
-
FastOutLinearInInterpolator (accelerated interpolation)
The difference with AccelerateInterpolator is that the initial acceleration is faster
-
FastOutSlowInInterpolator (acceleration deceleration interpolation)
Start faster
-
Continuous reduction (LinearOutSlowInInterpolator),
If you are not satisfied with the built-in interpolator, you can implement the TimeInterpolator interface for customization
Interpolator graph
Key words:
- When you Anticipate an animation, you drop below before you begin to run into it
- Overshoot indicates that the animation path exceeds the specified distance
- Decelerate speed
- Accelerate accelerated
- Linear average
- Bounce Bounce
- The Cycle repeated AccelerateDecelerateInterpolator effect executed repeatedly
Attribute animation
I said that the traditional animation plays in the same position but the view changes. In order to solve this problem, Google introduced property animation after Android3.0. Changes in the animation result in changes to the position properties of the control.
Property animation is based on the principle of reflection to get object property field modification (offset, transparent, rotate). For example, to modify the setXX() method of a View, XX needs to be passed as the parameter (PropertyName), so there is no ScaleAnimation or TranslateAnimation similar to Animation.
Key categories:
- Animator abstract class
- AnimatorSet Property animation set
- Animatorset. Builder builds more complex animation sets
- ValueAnimator Property animation
- ObjectAnimator Animator
- TimeAnimator time animation
- AnimatorSet Property animation set
Other classes
- AnimatorInflater AnimatorInflater
- AnimatorListener property animation listener
- The AnimatorListenerAdapter property is the adapter for the animation listener
- AnimatorPauseListener Animation visibility listener
The sample
You need to create an XML file in the RES/Animator directory
In fact, property animations in the anim directory can still be loaded and run, but with a warning
Attribute animation XML supports three types of tags :(XML tag and corresponding Java class)
- objectAnimator (ObjectAnimator)
- animator (ValueAnimator)
- set (AnimatorSet)
XML create animation
There is not much support for XML attributes for property animation
But object animation supports many properties, and can be played directly against the View animation;
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:propertyName="rotationY"
android:valueFrom="0"
android:valueTo="360"
android:valueType="floatType">
</objectAnimator>
Copy the code
All attributes (all support code completion, is it easier to use than Animation XML):
Meaning:
-
The duration of the
-
interpolator
-
PathData must be api21 or above
-
The property name
A string value, filled with the XXX string in the View’s setXXX method
-
Attribute values
-
PropertyXName must be at least API21
-
PropertyYName must be at least API21
-
Repeat the number
-
Repetitive patterns
-
Delay time
-
Attribute starting value
-
Attribute end value
-
The attribute types (ColorType/FloatType/IntType/PathType)
PathData propertyXName/propertyYName these three attributes are tie-in use; At the same time, Api21 or above is required to be effective.
I don’t know how it works;
Load the XML file to the view
Animator animator = AnimatorInflater.loadAnimator(getApplicationContext(),
R.animator.objectAnimator);
animator.setTarget(mImageView);
animator.start();
Copy the code
code
ObjectAnimator anim = ObjectAnimator.ofFloat(v, "scaleX".2f);// Double x
anim.setDuration(1000);/ / the length
anim.setRepeatCount(2);// Number of repetitions
anim.setRepeatMode(ValueAnimator.REVERSE);// Repeat in the opposite direction to the original appearance
anim.setInterpolator(new AccelerateInterpolator());// Set the interpolator to acceleration
anim.start();
Copy the code
ValueAnimator also supports creating animation configurations in XML, with consistent usage, but with fewer attributes.
Animator
This is the parent abstract class of all property animations and cannot be used directly.
// Copy the animation
Animator clone (a)
// Delay time
void setStartDelay (long startDelay)
long getStartDelay (a)
// Animation time per execution
Animator setDuration (long duration)
// If the animation is infinite, return -1(field :DURATION_INFINITE)
long getTotalDuration (a)
// Set the interpolator
void setInterpolator (TimeInterpolator value)
// Sets the target for animation execution
void setTarget (Object target)
Copy the code
Control animation playback
Control the life cycle of Animation is more freedom than Animation;
// Start animation
void start (a)
// Pause the animation
void pause (a)
// Continue animation
void resume (a)
void end (a)
// End the animation
void cancel (a)
// The difference between canceling an animation and ending an animation is that one more function, onCancel, is executed
Copy the code
The animation state
// Whether the status is not visible
boolean isPaused (a)
// Whether the animation is currently running
boolean isRunning (a)
boolean isStarted (a)
Copy the code
Lifecycle listeners
// Add an animation listener
void addListener (Animator.AnimatorListener listener)
// Add an animation visibility listener
void addPauseListener (Animator.AnimatorPauseListener listener)
// Get all listeners
ArrayList<Animator.AnimatorListener> getListeners (a)
// Delete all listeners
void removeAllListeners (a)
void removeListener (Animator.AnimatorListener listener)
void removePauseListener (Animator.AnimatorPauseListener listener)
Copy the code
The sample
animator.addListener(new Animator.AnimatorListener() {
@Override public void onAnimationStart(Animator animation) {
// Start animation
}
@Override public void onAnimationEnd(Animator animation) {
// End of animation
}
@Override public void onAnimationCancel(Animator animation) {
// The animation is cancelled
}
@Override public void onAnimationRepeat(Animator animation) {
// The animation repeats}});Copy the code
Pause and resume the listener
AnimatorPauseListener (AnimatorPauseListener) A listener to call back to when an animation is paused or continued
void onAnimationPause (Animator animation)
void onAnimationResume (Animator animation)
Copy the code
Add listeners. See the following method for Animato
void addPauseListener (Animator.AnimatorPauseListener listener)
Copy the code
Animation start and end values
The two methods differ depending on which class is being executed.
For example, ValueAnimator is invalid because it has no attribute information. The AnimationSet is passed to the child animation (when the child animation has no value set).
ObjectAnimator changes the value of the property based on its name.
// Animation start and end values
void setupStartValues (a)
void setupEndValues (a)
Copy the code
End or cancel the animation, but the callback method is inconsistent
// End the animation
void end (a)
// Unanimate
void cancel (a)
Copy the code
Can cancel the animation, but the callback method in the animation listener is inconsistent
-
end
Call the onAnimationEnd method
-
cancel
Call the onAnimationEnd and onAnimtionCacel methods
ValueAnimator
This is just a value operation that provides a more flexible transition effect
For example, in 1000 milliseconds Transition from a start value of 0 to 300 the end value change (change rate to comply with the default interpolator AccelerateDecelerateInterpolator) interpolator, of course, you can also set themselves up.
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f.100f.300f);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
Log.i("Log"."Value change:"+ animation.getAnimatedValue()); }}); valueAnimator.start();Copy the code
Output result:
ValueAnimator has animate characteristics (duration/interpolator), it only provides a smooth animation transition value, but it is up to you to change the object’s properties (margin/transparency/color value/width). This is why properties animation can control any object.
The ofFloat method is a variable parameter, and as long as you fill in a fixed value, you must start with the first parameter and end with the last parameter. And then the middle argument will run to.
Create ValueAnimator instances using methods such as ofxx(). This set of methods produces a default value transition effect.
ValueAnimator ofArgb (int. values)
ValueAnimator ofFloat (float. values)
ValueAnimator ofInt (int. values)
ValueAnimator ofObject (TypeEvaluator evaluator, Object... values)
// From the property value fixator
ValueAnimator ofPropertyValuesHolder (PropertyValuesHolder... values)
Copy the code
Property value change listener
void addUpdateListener (ValueAnimator.AnimatorUpdateListener listener)
void removeUpdateListener (ValueAnimator.AnimatorUpdateListener listener)
void removeAllUpdateListeners (a)
Copy the code
ValueAnimator’s listener calls back the parameter ValueAnimator to get the value of the animator’s changing property.
// Get the property values that are changing as the animation runs
Object getAnimatedValue (a)
// Get the attribute value based on the attribute name
Object getAnimatedValue (String propertyName)
// Get a property value holder
PropertyValuesHolder[] getValues (a)
Copy the code
Fraction this represents the degree of completion in ValueAnimator.
// The range is 0 to 1, indicating the progress percentage of the current time in the total time
float getAnimatedFraction (a)
Copy the code
Animation playback time
long getCurrentPlayTime (a)
// How long the animation has been playing
long getTotalDuration (a)
// How long it takes for all animations to finish playing
long getFrameDelay (a)
Copy the code
TypeEvaluator
TypeEvaluator is set up through the setEvaluator() method of ValueAnimator
void setEvaluator (TypeEvaluator value)
Copy the code
Interpolator Unlike interpolator controls velocity changes, type evaluators mainly control the specific starting and interpolating values of ValueAnimator.
Its internal method return value determines the value of getAnimatedValue().
TypeEvaluator is provided by default
- TypeEvaluator: Interface that needs to be implemented for user-defined attribute values
- IntEvaluator: indicates the integer attribute value
- FloatEvaluator: Floating-point property value
- ArgbEvaluator: hexadecimal value of the color attribute
- RectEvaluator: rectangle property value
Added type estimator after api21
- PointFEvaluator: Value of the coordinate property
- FloatArrayEvaluator
- IntArrayEvaluator
// Customize HslEvaluator
private class HsvEvaluator implements TypeEvaluator<Integer> {
float[] startHsv = new float[3];
float[] endHsv = new float[3];
float[] outHsv = new float[3];
@Override
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
// Convert ARGB to HSV
Color.colorToHSV(startValue, startHsv);
Color.colorToHSV(endValue, endHsv);
// Calculate the color value corresponding to the current animation completion (fraction)
if (endHsv[0] - startHsv[0] > 180) {
endHsv[0] - =360;
} else if (endHsv[0] - startHsv[0] < -180) {
endHsv[0] + =360;
}
outHsv[0] = startHsv[0] + (endHsv[0] - startHsv[0]) * fraction;
if (outHsv[0] > 360) {
outHsv[0] - =360;
} else if (outHsv[0] < 0) {
outHsv[0] + =360;
}
outHsv[1] = startHsv[1] + (endHsv[1] - startHsv[1]) * fraction;
outHsv[2] = startHsv[2] + (endHsv[2] - startHsv[2]) * fraction;
// Calculate the transparency corresponding to the current animation completion (fraction)
int alpha = startValue >> 24 + (int) ((endValue >> 24 - startValue >> 24) * fraction);
// Return HSV to ARGB
return Color.HSVToColor(alpha, outHsv);
}
}
ObjectAnimator animator = ObjectAnimator.ofInt(view, "color".0xff00ff00);
// Use a custom HslEvaluator
animator.setEvaluator(new HsvEvaluator());
animator.start();
Copy the code
ObjectAnimator
ValueAnimator does not directly control the animation of a View (it can only be set manually in the listener). ObjectAnimator is the most common action when a View loads an animation, so Google overwrites ValueAnimator and ObjectAnimator appears. A class that can modify properties of View objects directly by reflection;
It is reflection that requires the set
If there are no setters and getters, there are three solutions:
- Add these two functions from View
- Use a wrapper class
- Use ValueAnimator instead
Tip: You don’t have to have the get
Create the animation
The ofxx() function also creates animations, but differs from ValueAniamtor in that it supports direct setTarget targets;
color
This function limits api21
ObjectAnimator ofArgb (Object target,
String propertyName,
int. values)
ObjectAnimator ofArgb (T target,
Property<T, Integer> property,
int. values)
Copy the code
ObjectAnimator also has a type problem when setting property values. That is, what type of this property of the object, what type you use when you specify the start value and the start value in ObjectAnimator. Otherwise it won’t work.
Custom object
ObjectAnimator ofObject (T target, Property
property, TypeEvaluator
evaluator, V... values)
,>
ObjectAnimator ofObject (Object target, String propertyName, TypeConverter
converter, Path path)
,>
/ / limit api21
ObjectAnimator ofObject (T target, Property
property, TypeConverter
converter, Path path)
,>
,>
ObjectAnimator ofObject (T target, Property
property, TypeConverter
converter, TypeEvaluator
evaluator, V... values)
,>
,>
ObjectAnimator ofObject (Object target, String propertyName, TypeEvaluator evaluator, Object... values)
Copy the code
ObjectAnimator ofFloat (Object target,
String xPropertyName,
String yPropertyName,
Path path)
ObjectAnimator ofFloat (T target,
Property<T, Float> property,
float... values)
ObjectAnimator ofFloat (T target,
Property<T, Float> property,
float... values)
ObjectAnimator ofFloat (Object target,
String propertyName,
float... values)
Copy the code
The int value
ObjectAnimator ofInt (T target,
Property<T, Integer> xProperty,
Property<T, Integer> yProperty,
Path path)
ObjectAnimator ofInt (T target,
Property<T, Integer> property,
int... values)
ObjectAnimator ofInt (Object target,
String propertyName,
int... values)
ObjectAnimator ofInt (Object target,
String xPropertyName,
String yPropertyName,
Path path)
Copy the code
Multi
All functions limit API21
ObjectAnimator ofMultiFloat (Object target,
String propertyName,
float[][] values)
ObjectAnimator ofMultiFloat (Object target,
String propertyName,
Path path)
ObjectAnimator ofMultiFloat (Object target,
String propertyName,
TypeConverter<T, float[]> converter,
TypeEvaluator<T> evaluator,
T... values)
ObjectAnimator ofMultiInt (Object target,
String propertyName,
int[][] values)
ObjectAnimator ofMultiInt (Object target,
String propertyName,
Path path)
ObjectAnimator ofMultiInt (Object target,
String propertyName,
TypeConverter<T, int[]> converter,
TypeEvaluator<T> evaluator,
T... values)
Copy the code
PropertyValuesHolder
ObjectAnimator and ValueAnimator both have a PropertyValuesHolder method set;
Can save multiple animation properties and animation playback can execute multiple animations at the same time;
ObjectAnimator ofPropertyValuesHolder (Object target, PropertyValuesHolder... values)
ValueAnimator ofPropertyValuesHolder (PropertyValuesHolder... values)
Copy the code
Introduce the PropertyValuesHolder method. Mutable arguments are used in the same way as ObjectAnimator.
PropertyValuesHolder ofFloat (String propertyName,
float. values)
PropertyValuesHolder ofInt (String propertyName,
int. values)
PropertyValuesHolder ofMultiFloat (String propertyName,
float[][] values)
PropertyValuesHolder ofMultiInt (String propertyName,
int[][] values)
Copy the code
Example:
PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationX".300);
PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("scaleX".1f.0.1f);
PropertyValuesHolder pvh3 = PropertyValuesHolder.ofFloat("scaleY".1f.0.1f);
ObjectAnimator.ofPropertyValuesHolder(pvh1, pvh2, pvh3).setDuration(1000).start();
Copy the code
PropertyValueHolder can also be defined in an XML tag
<animator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:repeatCount="1"
android:repeatMode="reverse">
<propertyValuesHolder android:propertyName="x" android:valueTo="400"/>
<propertyValuesHolder android:propertyName="y" android:valueTo="200"/>
</animator>
Copy the code
KeyFrame
PropertyValuesHolder also sets keyframes to control the progress of animation playback;
Properties can be split into multiple segments for execution;
PropertyValuesHolder ofKeyframe (String propertyName, Keyframe... values)
PropertyValuesHolder ofKeyframe (Property property, Keyframe... values)
void setKeyframes (Keyframe... values)
Copy the code
Property belongs to the Property object containing name and Type
XML setup
<propertyValuesHolder android:propertyName="progress" >
<keyframe/>
<keyframe android:fraction="0.2"
android:interpolator="@android:anim/accelerate_interpolator"
android:value="300"/>
<keyframe android:interpolator="@android:anim/accelerate_interpolator"
android:value="1000" />
</propertyValuesHolder>
Copy the code
KeyFrame function
static Keyframe ofFloat(float fraction)
static Keyframe ofInt(float fraction)
static Keyframe ofObject(float fraction)
static Keyframe ofFloat(float fraction, float value)
static Keyframe ofInt(float fraction, int value)
static Keyframe ofObject(float fraction, Object value)
Copy the code
abstract Keyframe clone(a)
float getFraction(a)
Class getType(a)
/ / value types
abstract Object getValue(a)
/ / value
boolean hasValue(a)
// If there is a value
void setFraction(float fraction)
// Set the completion percentage
void setInterpolator(TimeInterpolator interpolator)
TimeInterpolator getInterpolator(a)
abstract void setValue(Object value)
Copy the code
Path animation
ObjectAnimator can also control the animation playback path
Move the control animation based on the drawn Path Path. Belongs to an extension of ObjectAnimator animation.
// Trigger the click event
public void startAnimator(View view) {
// Draw the path
Path path = new Path();
path.moveTo(100.100);
path.lineTo(200.100);
path.lineTo(200.200);
path.lineTo(300.300);
path.lineTo(50.50);
// Create a floating property animation
ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.X, View.Y, path);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setDuration(3000);
animator.start();
}
Copy the code
AnimatorSet
The attribute animation set controls the playing time of sub-animation more flexibly than the view animation set. Inherited Animator has the basic functionality of attribute animation;
XML tags
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="sequentially">
<objectAnimator
android:duration="3000"
android:propertyName="rotationX"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:startOffset="0"
android:valueFrom="0"
android:valueTo="90"
android:valueType="intType" />
</set>
Copy the code
The set tag has only one attribute. Android: Ordering indicates when the animation in the set is executed. Sequentially, sequentially, is executed together
And then reference the tag
Animator animator = AnimatorInflater.loadAnimator(this, R.animator.animator_set);
animator.setTarget(mButton);
animator.start();
Copy the code
You can do the same in your code
void playTogether (Animator... items)
void playSequentially (Animator... items)
Copy the code
Both methods take mutable arguments and can be passed N animated objects to play.
Here are two sample property animation sets
At the same time play
AnimatorSet set = new AnimatorSet();
set.playTogether(
ObjectAnimator.ofFloat(v, "x", startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(v, "y", startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(v, "scaleX", startScale, 1f))
.with(ObjectAnimator.ofFloat(v, "scaleY", startScale, 1f));
set.setDuration(200);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
//
}
@Override
public void onAnimationCancel(Animator animation) {
//}}); set.start();Copy the code
Order of play
Animator scaleXAnimator = ObjectAnimator.ofFloat(mImageView, "scaleX".1.0.5 f);
scaleXAnimator.setDuration(2000);
Animator scaleYAnimator = ObjectAnimator.ofFloat(mImageView, "scaleY".1.0.5 f);
scaleYAnimator.setDuration(2000);
Animator rotationXAnimator = ObjectAnimator.ofFloat(mImageView, "rotationX".0.360);
rotationXAnimator.setDuration(2000);
Animator rotationYAnimator = ObjectAnimator.ofFloat(mImageView, "rotationY".0.360);
rotationYAnimator.setDuration(2000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(scaleXAnimator)
.with(scaleYAnimator)
.before(rotationXAnimator)
.after(rotationYAnimator);
animatorSet.start();
Copy the code
All function
// Play N animations sequentially and sequentially
void playSequentially (List<Animator> items)
void playSequentially (Animator... items)
void playTogether (Collection<Animator> items)
void playTogether (Animator... items)
void setupStartValues (a)
void setupEndValues (a)
Copy the code
AnimatorSet.Builder
The property animation collection has a constructor that can be used to create sequentially executed animation collections
AnimatorSet.Builder play (Animator anim) // Create a constructor
Copy the code
Constructor function
AnimatorSet.Builder after(long delay)
// Delay playback
AnimatorSet.Builder after(Animator anim)
// Add the animation backwards
AnimatorSet.Builder before(Animator anim)
// Add animation forward
AnimatorSet.Builder with(Animator anim)
// Play animation at the same time
Copy the code
Here is a sample of official documentation:
Order of execution:
- The first play
bounceAnim
. - At the same time play
squashAnim1
.squashAnim2
.stretchAnim1
, andstretchAnim2
- And then play
bounceBackAnim
. - The last play
fadeAnim
.
AnimatorSet bouncer = new AnimatorSet();
bouncer.play(bounceAnim).before(squashAnim1);
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
bouncer.play(squashAnim1).with(stretchAnim2);
bouncer.play(bounceBackAnim).after(stretchAnim2);
ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha".1f.0f);
fadeAnim.setDuration(250);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(bouncer).before(fadeAnim);
animatorSet.start();
Copy the code
AnimatorInflater
Unlike the View animation (which uses an AnimationUtils utility class), the property animation uses a filler to load the XML animation resource.
There are only two static methods.
Animator loadAnimator (Context context,
int id)
StateListAnimator loadStateListAnimator (Context context,
int id)
Copy the code