Android-frame-by-frame animation, supplementary animation learning, android-by-Animation

Source: Internet
Author: User

Android-frame-by-frame animation, supplementary animation learning, android-by-Animation

I. frame-by-frame animation

Frame-by-frame animation is used to specify a series of Drawable objects used as the View background. It is similar to a slide.

PublicClassAnimationDrawableExtendsDrawableContainerImplementsRunnable, Animatable

PublicClassDrawableContainerExtendsDrawableImplementsDrawable. Callback

1. Application Example: 1. Create <animation-list> under the res/drawabe File
<?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/icon0" android:duration="500"/>    <item android:drawable="@drawable/icon1" android:duration="500"/>    <item android:drawable="@drawable/icon2" android:duration="500"/>    <item android:drawable="@drawable/icon3" android:duration="500"/></animation-list>

Android: When oneshot is false, it indicates loop playback. The default value is false.

2. Use frame-by-frame animation in the code
myImageView=(ImageView)findViewById(R.id.myImageView);myImageView.setBackgroundResource(R.drawable.myanimation);       AnimationDrawable animationDrawable =(AnimationDrawable) myImageView.getBackground();animationDrawable.start();//animationDrawable.stop();

Ii. extended knowledge: AnimationDrawable class

1. Provide functions:

public void start()public void stop()public boolean isRunning()public int getNumberOfFrames()public Drawable getFrame(int index)public int getDuration(int i)public boolean isOneShot()public void setOneShot(boolean oneShot)/**Add a frame to the animation */public void addFrame(Drawable frame, int duration)

2. You have defined a frame animation and how to play a certain number of Consecutive Frames. (For example, there are four frames in this article and two or three frames are played)

Analysis: The AnimationDrawable class provides the getFrame and getDuration methods, but does not provide the corresponding setter function to control the frame position for playback. The AnimationDrawable class has a private variable mCurFrame, which indicates the current playback frame. Definition:

/** The current frame, may be -1 when not animating. */    private int mCurFrame = -1;
Because it is a private variable and does not provide corresponding setter functions, reflection technology is used for read and write.
public class MyImageView extends ImageView{       private AnimationDrawable animationDrawable;     public MyImageView(Context context, AttributeSet attrs) {        super(context, attrs);        setBackgroundResource(R.drawable.myanimation);        animationDrawable = (AnimationDrawable) getBackground();               setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                animationDrawable.start();            }        });    }       @Override    public void onDraw(Canvas canvas)    {        try        {           Field field = AnimationDrawable.class.getDeclaredField("mCurFrame");           field.setAccessible(true);           int curFrame = field.getInt(animationDrawable);           if(curFrame == 2)              field.setInt(animationDrawable, 0);        } catch(Exception e)        {           Log.e("AnimationDrawable", e.toString());        }        super.onDraw(canvas);    } }

II. Compensation Animation: different from frame-by-frame animation, that is, the animation start and end state is set. One or four basic animations are added in the middle. 1. scale-ScaleAnimation Method 1: create an xml file in the res/anim file:
<! -- Scale --> <scale android: fromXScale = "0.0" android: toXScale = "1.0" android: fromYScale = "0.0" android: toYScale = "1.0" android: export Tx = "50%" android: effecty = "50%" android: duration = "1000" android: repeatCount = "-1" android: repeatMode = "reverse"/> <! -- FromXScale: scale the scale along the X and Y axes from-to --> <! -- Rotate TX: the center point of the zoom (percentage of the View Size) --> <! -- Duration: duration --> <! -- RepeatCount: number of repetitions. The default value is 0, indicating one rotation. If it is set to n, It is rotated n + 1. If it is set to-1 or infinite, it is an infinite loop. --> <! -- RepeatMode: repeatMode. The default value is restart. -->
Use in code:
    Animation animation =AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim_set);    myImageView.startAnimation(animation);

Method 2:
    ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1);    animation.setDuration(1000);    animation.setRepeatCount(-1);    animation.setRepeatMode(Animation.RESTART);    myImageView.startAnimation(animation);

The usage below is similar:

2. Transparency alpha --- AlphaAnimation

<! -- Transparency --> <alpha android: fromAlpha = "0.0" android: toAlpha = "1.0" android: duration = "1000" android: repeatCount = "-1" android: repeatMode = "reverse"/>
3. rotate --- RotateAnimation
<! -- Rotate --> <rotate android: fromDegrees = "0" android: toDegrees = "360" android: Release Tx = "50%" android: Upgrade ty = "50%" android: duration = "1000" android: repeatCount = "2" android: repeatMode = "restart"/>
4. Move translate --- TranslateAnimation
<! -- Mobile --> <translate android: fromXDelta = "0" android: toXDelta = "1000" android: fromYDelta = "0" android: toYDelta = "1000" android: duration = "1000"/>

2. Combination of several Anim Sets
<? Xmlversion = "1.0" encoding = "UTF-8"?> <Set xmlns: android = "http://schemas.android.com/apk/res/android" android: interpolator = "@ android: anim/accelerate_interpolator" android: repeatMode = "reverse" android: repeatCount = "2"> <! -- Mobile --> <translate android: fromXDelta = "0" android: toXDelta = "1000" android: fromYDelta = "0" android: toYDelta = "1000" android: duration = "1000"/> <! -- Scale --> <scale android: fromXScale = "0.0" android: toXScale = "1.0" android: fromYScale = "0.0" android: toYScale = "1.0" android: export Tx = "50%" android: Ty = "50%" android: duration = "1000"/> <! -- Transparency --> <alpha android: fromAlpha = "0.0" android: toAlpha = "1.0" android: duration = "1000"/> <rotate android: fromDegrees = "0" android: toDegrees = "360" android: durtx = "50%" android: Durty = "50%" android: duration = "1000"/> </set>
Android: interpolator is the iterator (animation Renderer) used for converting the start and end values of each animation. The default value is AccelerateDecelerateInterpolator, which can also be set through setInterpolator; AccelerateDecelerateInterpolator

An interpolator where the rate of change starts and ends slowly but accelerates through the middle

AccelerateInterpolator: starts slowly and then accelerates

An interpolator where the rate of change starts out slowly and then accelerates.

AnticipateInterpolator: backward at the beginning, and then rush forward

An interpolator where the change starts backward then flings forward.

AnticipateOvershootInterpolator: Return to the final value after a certain value is rushed forward.

An interpolator where the change starts backward then flings forward and overshoots the target value and finally goes back to the final value.

BounceInterpolator: pops up when the animation ends.

An interpolator where the change bounces at the end.

DecelerateInterpolator; Speed up At the beginning, and then slow down

An interpolator where the rate of change starts out quickly and then decelerates.

LinearInterpolator; constant speed

An interpolator where the rate of change is constant

OvershootInterpolator; start to rush forward, exceed the final value, and then return

An interpolator where the change flings forward and overshoots the last value then comes back.


3. Add the animation listener AnimationListener

Animation. setAnimationListener (new AnimationListener () {@ Override public void onAnimationStart (Animation animation) {Log. I ("AnimationListener", "Animation start") ;}@ Override public void onAnimationRepeat (animation Animation) {Log. I ("AnimationListener", "Duplicate Animation") ;}@ Override public void onAnimationEnd (animation Animation) {Log. I ("AnimationListener", "animation ends ");}});
4. Add an animation LayoutAnimation for ViewGroup: 1. Create an xml file: layout_anim.xml under res/anim.
<? Xmlversion = "1.0" encoding = "UTF-8"?> <LayoutAnimation xmlns: android = "http://schemas.android.com/apk/res/android" android: delay = "1.0" android: animationOrder = "random" android: animation = "@ anim/anim_set"/> <! -- Delay subclass animation time interval (latency) --> <! -- Display method of the animationOrder subclass: normal (0 default) reverse (1 reverse order) random (2 random) --> <! -- Animation: Corresponding animation -->
2. Use: write in the layout interface layout of the activity:
    android:layoutAnimation="@anim/layout_anim"
3. Use in Java code:

<Add an animation for ListView (subclass of ViewGroup)>

    String[] mMenuItemStr = { "Bear", "Bird", "Cat", "Tigers", "Panda" ,"Bear", "Bird", "Cat", "Tigers", "Panda"};    listView.setAdapter(new ArrayAdapter<String>(this, R.layout.item_left_menu,mMenuItemStr));     Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_set);    LayoutAnimationController controller = new LayoutAnimationController(animation);    controller.setOrder(LayoutAnimationController.ORDER_NORMAL);    controller.setDelay(1);    listView.setLayoutAnimation(controller);
4. The implementation effect is to add an animation to each sub-View in the ViewGroup and load it according to Random and other methods.

5. When ViewGroup is layout for the first time, the layout animation is loaded. You can use listView. scheduleLayoutAnimation (); to force it to execute again.

6. Add an animation listener:

     listView.setLayoutAnimationListener(new AnimationListener() {                       @Override            publicvoid onAnimationStart(Animation animation) {                           }                       @Override            publicvoid onAnimationRepeat(Animation animation) {                           }                       @Override            publicvoid onAnimationEnd(Animation animation) {                           }        });

5. Expansion: 1. How to enable two supplementary Animations (anim1.xml and anim2.xml) to play the other one immediately after one animation is played. Use an animation listener and rewrite the onAnimationEnd method.
private Animation animation1, animation2;       privateclass myAnimationListener implements AnimationListener    {        @Override        publicvoid onAnimationStart(Animation animation) {                   }        @Override        publicvoid onAnimationEnd(Animation animation) {            if(animation.hashCode() == animation1.hashCode())                myImageView.startAnimation(animation2);            else                myImageView.startAnimation(animation1);        }        @Override        publicvoid onAnimationRepeat(Animation animation) {                   }          }
Used in Activity:
        animation1 = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim1);        animation2 = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim2);        myAnimationListener myAnimationListener = new myAnimationListener();        animation1.setAnimationListener(myAnimationListener);        animation2.setAnimationListener(myAnimationListener);        myImageView.startAnimation(animation1);
2. Custom Animation Renderer interpolator
Private class myInterpolator implements Interpolator {@ Override public float getInterpolation (floatinput) {/** input: value range: 0.0-1.0, indicating the loading progress of the animation * return value: <1.0 indicates that the target point has not been reached; closer to 1.0 indicates that it is closer to the target point; greater than 1.0 indicates that the animation object has exceeded the target point **/if (input <= 0.5) return input * input; else return (1-input) * (1-input );}}
Use in the Code:
    Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim1);    animation.setInterpolator(new myInterpolator());    myImageView.startAnimation(animation);
Compare the source code of AccelerateInterpolator:
/** * An interpolator where the rate of change starts out slowly and * and then accelerates. * */@HasNativeInterpolatorpublic class AccelerateInterpolator implements Interpolator, NativeInterpolatorFactory {    private final floatmFactor;    private final doublemDoubleFactor;     public AccelerateInterpolator() {        mFactor = 1.0f;        mDoubleFactor = 2.0;    }     /**     * Constructor     *     * @param factor Degree to which the animation should be eased. Seting     *        factor to 1.0f produces a y=x^2 parabola. Increasing factor above     *        1.0f  exaggerates the ease-in effect (i.e., it starts even     *        slower and ends evens faster)     */    public AccelerateInterpolator(floatfactor) {        mFactor = factor;        mDoubleFactor = 2 * mFactor;    }     public AccelerateInterpolator(Context context, AttributeSet attrs) {        this(context.getResources(), context.getTheme(), attrs);    }     /** @hide */    public AccelerateInterpolator(Resources res, Theme theme, AttributeSet attrs) {        TypedArray a;        if (theme != null) {            a = theme.obtainStyledAttributes(attrs, R.styleable.AccelerateInterpolator, 0, 0);        } else {            a = res.obtainAttributes(attrs, R.styleable.AccelerateInterpolator);        }         mFactor = a.getFloat(R.styleable.AccelerateInterpolator_factor, 1.0f);        mDoubleFactor = 2 * mFactor;         a.recycle();    }     public float getInterpolation(float input) {        if (mFactor == 1.0f) {            return input * input;        } else {            return (float)Math.pow(input, mDoubleFactor);        }    }     /** @hide */    @Override    public long createNativeInterpolator() {        return NativeInterpolatorFactoryHelper.createAccelerateInterpolator(mFactor);    }}




























Zookeeper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.