Android frame animation practice

First create a drawable file and add a resource 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="@color/rate_01"
        android:duration="16"/>
    <item android:drawable="@color/rate_02"
        android:duration="16"/>
    <item android:drawable="@color/rate_03"
        android:duration="16"/>
</animation-list>

layout settings

<ImageView
        android:id="@+id/my_anim"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/my_anima"
        />

Control animation in code

AnimationDrawable drawable = (AnimationDrawable) binding.myAniView.getDrawable();
        drawable.start();
        drawable.stop();

Start animation
Pause

Listen to the end of the animation and switch to the next animation. AnimationDrawable itself has no animation end monitoring, you can customize AnimationDrawable

public class AnimationDrawableLife extends AnimationDrawable {
    
    
    private AnimationEndListener listener;


    AnimationDrawableLife(AnimationEndListener listener) {
    
    
        this.listener = listener;
    }

    @Override
    public boolean selectDrawable(int index) {
    
    
        if (index != 0 && index == getNumberOfFrames() - 1) {
    
    
            if (listener != null) listener.onAnimationEnd();
        }
        return super.selectDrawable(index);
    }

    interface AnimationEndListener {
    
    
        void onAnimationEnd();
    }
}

use

AnimationDrawableLife animationDrawableLife = new AnimationDrawableLife(new AnimationDrawableLife.AnimationEndListener() {
    
    
            @Override
            public void onAnimationEnd() {
    
    
                binding.myAniView.setImageDrawable(animationDrawable);
                animationDrawable.start();
            }
        });
        binding.myAniView.setBackground(animationDrawableLife);
        animationDrawableLife.start();

Guess you like

Origin blog.csdn.net/weixin_44380181/article/details/129719075