15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アニメーションの完了が分かるAnimationDrawer

Posted at

#完了が通知されないフレームアニメーション
久しぶりにネィティブANdroidに帰ってきて不便を感じたのがフレームアニメーションの完了が感知できない件。

AnimationDrawableのソースとにらめっこしながら半日、色々やってみたけど、ここのフォーラムにある時間を計測するのがもっともスマートだと判明。

InformStateAnimationDrawable.java
/**
 * InformStateAnimationDrawable
 *
 * Created by hoshi_7 on 2014/07/31.
 */
public class InformStateAnimationDrawable extends AnimationDrawable{
    private OnAnimationStateListener mListener;
    private Handler mHandler;

    public InformStateAnimationDrawable(AnimationDrawable drawable) {
        mHandler = new Handler();
        for (int index = 0; index < drawable.getNumberOfFrames(); index++) {
            this.addFrame(drawable.getFrame(index)
                          , drawable.getDuration(index));
        }
    }

    public void setOnAnimationStateListener(OnAnimationStateListener listener){
        mListener = listener;
    }

    @Override
    public void start() {
        super.start();
        if(mListener != null) {
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    mListener.onAnimationEnd();
                }
            }, getTotalDuration());
        }
    }

    public int getTotalDuration() {
        int duration = 0;
        for (int i = 0; i < this.getNumberOfFrames(); i++) {
            duration += this.getDuration(i);
        }

        return duration;
    }

    public interface OnAnimationStateListener {
        public void onAnimationEnd();
    }

}

OnAnimationStateListenerという大層なインタフェースなのは途中のフレームが完了するタイミングにもイベントを飛ばす機会があるかもしれないので、あったらonAnimationFrame(int index);とかを足そうと思っていたから。

アクティビティ側

Activity.java
//AnimationDrawableからAnimationDrawableのサブクラスへの直接キャストできないのでこの作り

AnimationDrawable animDrawable = (AnimationDrawable)getResources().getDrawable(R.drawable.sample_anim);
InformStateAnimationDrawable frameAnimation = new InformStateAnimationDrawable(animDrawable);

//OnAnimationStateListenerインタフェースの実装をsetする
frameAnimation.setOnAnimationStateListener(new InformStateAnimationDrawable.OnAnimationStateListener() {
    @Override
    public void onAnimationEnd() {
       //アニメーション終了時の処理
    }
});

//リソースセット
mTodayLogo.setImageDrawable(frameAnimation);
//アニメーションスタート
frameAnimation.start();
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?