Chapter 2 CustomView view animation

1, View animation label

summary:

Android's view animation consists of five types: alpha, scale, translate, rotate, set

1. Configure XML animation file

• alpha: gradient transparency animation effect
 • scale: animation effect of gradual size scaling
 • translate: animation effect of moving the position of picture transformation
 • rotate: picture transfer rotation animation effect
 • set: define animation set

R.anim.scaleanim:

<scale xlmns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.4"
    android:fromYScale="0.0"
    android:toYScale="1.4"
    android:duration="700" />
TextView tv = (TextView) findViewById(R.id.tv);
// Load animation first
Animation animation = AnimationUtils.loadAnimation(MyActivity.this, R.anim.scaleanim);
// Start animation
tv.startAnimation(animation);

scale label:

•  android:fromXScale : the scale of the control relative to itself in the X-axis direction at the beginning of the animation, floating-point value.
•  android:toXScale : at the end of the animation, the scale of the control relative to itself in the X-axis direction, floating-point value.
• android:fromYScale
• android:toYScale
 •  android:pivotX : scale the X-axis coordinate of the starting point, which can be in three styles: numerical value, percentage, percentage P, such as 50, 50%, 50%p.
                  If it is a numerical value, it means that 50px is added at the upper left corner of the current view, i.e. the origin, as the X-axis coordinate of the scaling starting point.
                  If it is 50%, it means adding 50% of its width to the upper left corner of the current control as the X-axis coordinate of the scaling starting point.
                  If it is 50%p, it means adding 50% of the width of the parent control to the upper left corner of the current control as the X-axis coordinate of the scaling starting point.
•  android:pivotY : scale the Y coordinate of the starting point.

1. Relevant parameters of scale tag

<scale xlmns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="1.0"
    android:toXScale="0.4"
    android:fromYScale="1.2"
    android:toYScale="0.6"
    android:duration="700" />

At the beginning, in the X-axis direction, scale from 1 times the original width to 0.4 times the size, 1 times the size is the original size; in the Y-axis direction, scale from 1.2 times the original height to 0.6 times the size.

2. The meaning of taking different values for pivot X and pivot y

In the scale tab, pivotX and pivotY are used to specify the start coordinates of the animation.

1) When the value is value (50)

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.4"
    android:fromYScale="0.0"
    android:toYScale="1.4"
    android:pivotX="50"
    android:pivotY="50"
    android:duration="700" />

By default, the starting point of the animation is the coordinate origin of the upper left corner of the control, while pivotX and pivotY are used to specify the relative position of the starting point of the animation and the coordinate origin.

In this case, 50px is added to the starting point in the positive direction of X axis and Y axis on the basis of coordinate origin.

   

By comparing the above effects, it is obvious that only the attributes of pivot x = 50 and pivot y = 50 are added, but the state at the end of the animation is the same, only the points at the beginning of the animation are different. When the attribute pivotx = 50 and pivoty = 50 is added, the [animation start position] becomes a position with the upper left corner of the control as the origin and the coordinates as (50,50).

The following figure is an effect picture at the end of the animation. The white box indicates the initial state of the control, and the black dot position is the position at the beginning of the animation. It can be seen that the ending position of the animation is the same, but the scaling speed of X-axis and Y-axis will be dynamically adjusted according to the different starting position.

2) When the value is percentage (50%)

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.4"
    android:fromYScale="0.0"
    android:toYScale="1.4"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="700" />

Animation start position:

Its position is based on the coordinate origin, increasing 50% of its width and 50% of its height. Because the width and height of the TextView control are equal, the starting point is at the center of the control.

3) When the value is percentage p (50%p)

When the value is added with a letter p after the percentage, it means that the cardinality of the value is the parent control, that is, the value added on the basis of the origin is the percentage value of the parent control.

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.4"
    android:fromYScale="0.0"
    android:toYScale="1.4"
    android:pivotX="50%p"
    android:pivotY="50%p"
    android:duration="700" />

      

The starting point coordinate is based on the control coordinate origin plus 50% of the parent control width and 50% of the parent control height.

From these renderings, it can be seen that no matter what the value of pivot X or pivot y is, it only affects the starting position of the animation, and the ending position will not change.

3.Animation inheritance property

android.view.animation.Animation

public abstract class Animation extends Object implements Cloneable
----------------------------------
Known direct subclasses: 
AlphaAnimation, AnimationSet, RotateAnimation, ScaleAnimation, TranslateAnimation

All animations are inherited from the Animation class, that is, the Animation class is the base class of all animations (scale, alpha, translate, rotate).

•  android:duration : sets the duration, in milliseconds, for completing an animation.
•  android:fillAfter : if set to true, the state at the end of the control's animation is maintained.
•  android:fillBefore : if set to true, when the control animation ends, it reverts to the initialization state.
•  android:fillEnabled : and android:fillBefore The effect is the same. When the control animation ends, it will revert to the initialization state.
•  android:repeatCount : used to specify the number of iterations of the animation. When the value is infinite, it means infinite loop.
•  android:repeatMode : used to set the type of repetition. There are two values: reverse and restart. Among them, reverse means reverse playback; 
                      restart means replay and must be used with repeatCount to see the effect.
•  android:interpolator : used to set the interpolator, which is actually the specified animation effect, such as bounce effect.

1)android:fillAfter

2)android:fillBefore

3)android:repeatMode="restart"

4)android:repeatMode="reverse"

alpha label:

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="1.0"
    android:toAlpha="0.1"
    android:duration="3000"
    android:fillBefore="true" />

rotate label:

One android:fromDegrees And android:toDegrees Properties

•  android:fromDegrees : the angle position when the animation starts to rotate, positive clockwise, negative anticlockwise
• android:toDegrees
• android:pivotX
• android:pivotY
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="-650"
    android:duration="3000"
    android:fillBefore="true" />

Two android:pivotX And android:pivotY attribute

There are still three values for these two attributes: value, percentage and percentage p. They are used in the rotate tab to specify the animation rotation center coordinates.

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="-650"
    android:pivotX="100%"
    android:pivotY="100%"
    android:duration="3000"
    android:fillBefore="true" />

translate label:

In addition to the attributes inherited from the Animation class, the attributes of the tag are as follows:

•  android:fromXDelta : the X-axis coordinate of the starting point, which can be in three styles: numerical value, percentage and percentage p.
•  android:fromYDelta : Y coordinate of starting point
 •  android:toXDelta : end X coordinate
 •  android:toYDelta : end Y coordinate
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="-80"
    android:fromYDelta="0"
    android:toYDelta="-80"
    android:duration="2000" />

set label:

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="3000"
    android:fillAfter="true">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
    <scale
        android:fromXScale="0.0"
        android:toXScale="1.4"
        android:fromYScale="0.0"
        android:toYScale="1.4"
        android:pivotX="50%"
        android:pivotY="50%" />
    <rotate
        android:fromDegrees="0"
        android:toDegrees="720"
        android:pivotX="50%"
        androdi:pivotY="50%" />
</set>

The above code completes the combination effect of turning the control from small to large, rotating it out of the field, and changing the transparency from 0 to 1.

Note: it is invalid to set the repeatCount property in the set tag, which must be set separately for each animation.

2, Code implementation of view animation

Overview:

The labels and corresponding classes are shown in the following table:

These animations are derived from the Animation class, and the methods in the Animation class are common to these animations.

The corresponding relationship between tag attributes and methods in the Animation class is shown in the following table:

➋ScaleAnimation:

The ScaleAnimation class has the following constructors:

ScaleAnimation(Context context, AttributeSet attrs)
ScaleAnimation(float fromX, float toX, float fromY, float toY)
ScaleAnimation(float fromX, float toX, float fromY, float toY, float pivotX, float pivotY)
ScaleAnimation(float fromX, float toX, float fromY, float toY, 
               int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)

The first constructor is used to load animation from a local XML file, which is basically not used.

label android:pivotX There are three values: value, percentage and percentage p, which are embodied in the constructor, that is, the pivotXType parameter, which has three values: Animation.ABSOLUTE (corresponding to specific value) Animation.RELATIVE_TO_SELF (corresponding percentage) Animation.RELATIVE_TO_PARENT (corresponding percentage p).

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.4"
    android:fromYScale="0.0"
    android:toYScale="1.4"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="700" />

Construct the same effect with code:

TextView tv = (TextView) findViewById(R.id.tv);
ScaleAnimation scaleAnim = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
                                              Animation.RELATIVE_TO_SELF, 0.5f,
                                              Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnim.setDuration(700);
tv.startAnimation(scaleAnim);

➌AlphaAnimation:

AlphaAnimation(Context context, AttributeSet attrs)
AlphaAnimation(float fromAlpha, float toAlpha)
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="1.0"
    android:toAlpha="0.1"
    android:duration="3000"
    android:fillBefore="true" />

Construct the same effect with code:

TextView tv = (TextView) findViewById(R.id.tv);
AlphaAnimation alphaAnim = new AlphaAnimation(1.0f, 0.1f);
alphaAnim.setDuration(3000);
alphaAnim.setFillBefore(true);
tv.startAnimation(alphaAnim);

➍RotateAnimation:

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, float pivotXValue,
                int pivotYType, float pivotYValue)
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="-650"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="3000"
    android:fillBefore="true" />

Construct the same effect with code:

TextView tv = (TextView) findViewById(R.id.tv);
RotateAnimation rotateAnim = new RotateAnimation(0, -650,
                                                 Animation.RELATIVE_TO_SELF, 0.5f,
                                                 Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnim.setDuration(3000);
rotateAnim.setFillAfter(true);
tv.startAnimation(rotateAnim);

➎TranslateAnimation:

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)
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="-80"
    android:fromYDelta="0"
    android:toYDelta="-80"
    android:duration="2000"
    android:fillBefore="true" />

Construct the same effect with code:

TextView tv = (TextView) findViewById(R.id.tv);
TranslateAnimation translateAnim = new TranslateAnimation(Animation.ABSOLUTE, 0,
                                                          Animation.ABSOLUTE, -80,
                                                          Animation.ABSOLUTE, 0,
                                                          Animation.ABSOLUTE, -80);
translateAnim.setDuration(2000);
translateAnim.setFillBefore(true);
tv.startAnimation(translateAnim);

➏AnimationSet:

AnimationSet(Context context, AttributeSet attrs)
AnimationSet(boolean shareInterpolator)
------------------------—
• shareInterpolator: true Indicates that all animations below share the interpolator;
                     false Indicates that the animation below it defines its own interpolator.
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="3000"
    android:fillAfter="true">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
    <scale
        android:fromXScale="0.0"
        android:toXScale="1.4"
        android:fromYScale="0.0"
        android:toYScale="1.4"
        android:pivotX="50%"
        android:pivotY="50%" />
    <rotate
        android:fromDegrees="0"
        android:toDegrees="720"
        android:pivotX="50%"
        androdi:pivotY="50%" />
</set>

Construct the same effect with code:

TextView tv = (TextView) findViewById(R.id.tv);
Animation alphaAnim = new AlphaAnimation(1.0f, 0.1f);
Animation scaleAnim = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
                                         Animation.RELATIVE_TO_SELF, 0.5f,
                                         Animation.RELATIVE_TO_SELF, 0.5f);
Animation rotateAnim = new RotateAnimation(0, 720,
                                           Animation.RELATIVE_TO_SELF, 0.5f,
                                           Animation.RELATIVE_TO_SELF, 0.5f);
AnimationSet setAnim = new AnimationSet(true);
setAnim.addAnimation(alpahAnim);
setAnim.addAnimation(scaleAnim);
setAnim.addAnimation(rotateAnim);

setAnim.setDuration(3000);
setAnim.setFillAfter(true);

tv.startAnimation(setAnim);

➐Animation:

In fact, the Animation class has some properties and functions for us to use.

void cancle() // Cancel animation
void reset() // Reset the control to its state before the animation starts
void setAnimationListener(Animation.AnimationListener listener) // Set up animation listener
----------------------------------------
Animation.AnimationListener The callback function in is as follows:
abstract void onAnimationEnd(Animation animation) // Callback at end of animation
abstract void onAnimationRepeat(Animation animation) // Callback on animation repeat
abstract void onAnimationStart(Animation animation) // Callback at start of animation
final RotateAnimation rotateAnim = new RotateAnimation(0, -650, 
                                                       Animation.RELATIVE_TO_SELF, 0.5f,
                                                       Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnim.setDuration(3000);
rotateAnim.setFillAfter(true);
ScaleAnimation scaleAnim = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f, 
                                              Animation.RELATIVE_TO_SELF, 0.5f, 
                                              Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnim.setDuration(700);
scaleAnim.setAnimationListener(new Animation.AnimationListener() {
    public void onAnimationStart(Animation animation) {
    }

    public void onAnimationEnd(Animation animation) {
        tv.startAnimation(rotateAnim);
    }

    public void onAnimationRepeat(Animation animation) {
    }
});
tv.startAnimation(scaleAnim);
}

Let the control realize the scale animation first, then the rotation animation.

3, On interpolator

Is the change rate of animation uniform? How is the animation rate of change specified?

The rate of change of animation is determined by the interpolator class. Interpolator is called interpolator, also called accelerator, which is used to specify how the animation changes.

Interpolator is just an interface, through which you can customize the change rate of animation.

The system provides the following classes that have implemented interpolators:

There are two ways to use interpolators:

Method 1: reference interpolator in XML file

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="1.0"
    android:toAlpha="0.1"
    android:duration="3000"
    android:fillBefore="true"
    android:interpolator="@android:anim/accelerate_interpolator" />

Method 2: set interpolator through setInterpolator() function

TextView tv = (TextView) findViewById(R.id.tv);
AlphaAnimation alphaAnim = new AlphaAnimation(1.0f, 0.1f);
alphaAnim.setDuration(3000);
alphaAnim.setFillBefore(true);
alphaAnim.setInterpolator(new LinearInterpolator());
tv.startAnimation(alphaAnim);

➊AccelerateDecelerateInterpolator

Acceleration deceleration interpolator indicates that the speed changes slowly at the beginning and the end, and accelerates in the middle.

  (tangent of curve slope represents speed value)

TextView tv = (TextView) findViewById(R.id.tv);
Animation tranlateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translateanim);
tranlateAnim.setInterpolator(new AccelerateDecelerateInterpolator());
tv.startAnimation(tranlateAnim);

For rotation animation, transparency change, scale animation, it is also the initial acceleration, later slow.

➋AccelerateInterpolater

Acceleration interpolator.

➌DecelerateInterpolator

Deceleration interpolator.

➍LinearInterpolator

Linear interpolator, i.e. constant speed accelerator.

➎BounceInterpolator

Bounce interpolator. The springback effect of the control after free falling is simulated.

➏AnticipateInterpolator

Initial offset interpolator. Indicates that the animation is offset a distance forward at the beginning of the animation, and then the animation is applied.

Anticopateinterpolator also has a parameter constructor:

public AnticipateInterpolator(float tension)
• tension: Represents the tension value. The default value is 2. The larger the value is, the larger the initial offset is, and the faster the speed is.

➐OvershootInterpolator

Is the end offset interpolator, which means that at the end of the animation, continue to move a distance along the animation direction before ending the animation.

➑AnticipateOvershootInterpolator

AnticipateOvershootInterpolator = AnticipateInterpolator + OvershootInterpolator.

There are two other constructors with parameters for anticopateovershootinterpolator:

public AnticipateOvershootInterpolator(float tension)
public AnticipateOvershootInterpolator(float tension, float extraTension)
• tension: Tension value. The default value is 2. The larger the value, the greater the offset at the beginning and end, and the faster the speed
• extraTension: Extra tension value, default is 1.5

➒CycleInterpolator

Loop interpolator. Indicates that the animation cycle plays a specific number of times, and the speed changes along the sine curve.

public CycleInterpolator(float cycles)
• cycles: Number of cycles

(the mathematical curve that circulates twice, the part that dotted line frame is a cycle)

4, Animation example

1. Lens from far to near

<LinearLayout>
    <ImageView
        android:id="@+id/img"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/scenery"
        android:scaleType="fitXY" />
</LinearLayout>
ImageView imgView = (ImageView) findViewById(R.id.img);
ScaleAnimation scaleAnim = nwe ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f,
                                              Animation.RELATIVE_TO_SELF, 0.5f,
                                              Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnim.setFillAfter(true);
scaleAnim.setInterpolator(new BounceInterpolator());
scaleAnim.setDuration(6000);
imgView.startAnimation(scaleAnim);

2. Loading frame effect

<LinearLayout>
    <ImageView
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/loading" />
</LinearLayout>

(loading.png)

ImageView imgView = (ImageView) findViewById(R.id.loading);
RotateAnimation rotateAnim = nwe RotateAnimation(0, 360,
                                                 Animation.RELATIVE_TO_SELF, 0.5f,
                                                 Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnim.setRepeatCount(Animation.INFINITE);
rotateAnim.setDuration(2000);
rotateAnim.setInterpolator(new LinearInterpolator());
imgView.startAnimation(rotateAnim);

3. Scan animation

<FrameLayout
    android:background="#f8f8f8">
    <ImageView
        android:id="@+id/circle1"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@drawable/scan_circle"/>
    <ImageView
        android:id="@+id/circle2"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:clickable="true"
        android:src="@drawable/scan_circle"/>
    <ImageView
        android:id="@+id/circle3"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:clickable="true"
        android:src="@drawable/scan_circle"/>
    <ImageView
        android:id="@+id/circle4"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:clickable="true"
        android:src="@drawable/scan_circle"/>
    <ImageView
        android:id="@+id/start_can"
        android:layout_width="155dp"
        android:layout_height="155dp"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@drawable/scan_cover"/>
</FrameLayout>

In terms of layout, the four ImageView controls are hidden behind the buttons. Their background is a circle constructed by shape labels, and the fill color is yellow (scan_circle.xml)

<shape android:shape="oval">
    <solid android:color="#FF6C2F" />
</shape>

Look at the animation content (scale_ alpha_ anim.xml ), the animation effect is to enlarge the edge and reduce the transparency.

<set android:duration="3000">
    <scale
        android:repeatCount="infinite"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="3"
        android:toYScale="3" />
    <alpha
        android:repeatCount="infinite"
        android:fromAlpha="0.4"
        android:toAlpha="0" />
</set>

When the button is clicked, each ImageView control is animated at intervals.

final Animation animation1 = AnimationUtils.loadAnimation(ScannerDemo.this,R.anim.scale_alpha_anim);
final Animation animation2 = AnimationUtils.loadAnimation(ScannerDemo.this,R.anim.scale_alpha_anim);
final Animation animation3 = AnimationUtils.loadAnimation(ScannerDemo.this,R.anim.scale_alpha_anim);
final Animation animation4 = AnimationUtils.loadAnimation(ScannerDemo.this,R.anim.scale_alpha_anim);

final ImageView circle1 = (ImageView)findViewById(R.id.circle1);
final ImageView circle2 = (ImageView)findViewById(R.id.circle2);
final ImageView circle3 = (ImageView)findViewById(R.id.circle3);
final ImageView circle4 = (ImageView)findViewById(R.id.circle4);

findViewById(R.id.start_can).setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        circle1.startAnimation(animation1);

        animation2.setStartOffset(600);
        circle2.startAnimation(animation2);

        animation3.setStartOffset(1200);
        circle3.startAnimation(animation3);

        animation4.setStartOffset(1800);
        circle4.startAnimation(animation4);
    }
});

From the effect picture, it can be seen that each circle is animated at intervals, so use:

Animation.setStartOffset(int time);
------------------
Delay the start time of the animation

Delay the start time of each animation so that each animation can be separated from each other.

5, Frame by frame animation

XML implementation:

1. Overview

When using XML to define frame by frame animation, there are generally the following steps.

1) Define XML animation file

Define frame by frame animation through XML, the syntax is as follows:

<animation-list
    android:oneshot=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource_name"
        android:duration="integer" />
</animation-list>

2) Set ImageView

Either through android:src It can also be realized through android:background realization.

// By setting as a picture resource:
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/playing_ani"/>
// By setting as picture background:
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/playing_ani"/>

3) AnimationDrawable start animation

ImageView image = (ImageView) findViewById(R.id.frame_image);
AnimationDrawable anim = (AnimationDrawable) image.getDrawable();
anim.start();

If passed android:src Set the animation resource. The corresponding retrieval method is: image.getDrawable();

If passed android:background Set the animation resource. The corresponding retrieval method is: image.getBackground();

2. Example: music playing effect

Picture material:

playing_ani.xml:

<?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/list_icon_gif_playing1" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing2" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing3" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing4" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing5" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing6" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing7" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing8" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing9" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing10" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing11" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing12" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing13" android:duration="60"/>
    <item android:drawable="@drawable/list_icon_gif_playing14" android:duration="60"/>
</animation-list>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center_horizontal">

    <ImageView
            android:id="@+id/frame_image"
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/playing_ani"/>
</LinearLayout>
ImageView image = (ImageView) findViewById(R.id.frame_image);
AnimationDrawable anim = (AnimationDrawable) image.getBackground();
anim.start();

3.AnimationDrawable class

In Android, frame by frame animation needs to be supported by the animationdrawable class, which is located in android.graphics.Drawable The. Animationdrawable package is an indirect subclass of Drawable. It is mainly used to create a frame by frame animation, and can stretch the frame, set it as the View background, and then use AnimationDrawable.start() method.

AnimationDrawable has the following common functions:
• void start(): start playing frame by frame animation
 • void stop(): stop playing frame by frame animation
 • int getDuration(int index): get the duration of the frame of the specified index
 • Drawable getFrame(int index): get the Drawable object corresponding to the frame of the specified index
 • int getNumberOfFrames(): get all frames of the current AnimationDrawable
 • boolean isRunning(): judge whether the current AnimationDrawable is playing
 • void setOneShot(boolean oneShot): set whether AnimationDrawable can only execute once, true: execute once; false: loop play
 • boolean isOneShot(): judge whether the current AnimationDrawable is executed once
 • void addFrame(Drawable frame, int duration): add 1 frame for AnimatinDrawable and set the duration

Code implementation:

First, let's look at a function getIdentifier():

int getIdentifier(String name, String defType, String defPackage)
• Name: the name of the resource to find the resource ID
 • defType: the file type of the resource
           "Drawable" is under the drawable series folder,
           Under the anim folder is "anim",
           string.xml It's "string",
           array.xml It's "array"
• defPackage: application package name
 Returns the resource ID or 0 if no resource is specified.
ImageView image = (ImageView) findViewById(R.id.frame_image);
AnimationDrawable anim = new AnimationDrawable();
for (int i=1; i<=14; i++) {
    int id = getResources().getIdentifier("list_icon_gif_playing" + i, "drawable", getPackageName();
    Drawable drawable = getResources().getDrawable(id);
    anim.addFrame(drawable, 60);
}
anim.setOneShot(false);
image.setBackgroundDrawable(anim);
anim.start();

Tags: Android xml Attribute encoding

Posted on Sat, 06 Jun 2020 02:43:32 -0400 by srinivas6203