gpt4 book ai didi

Android AnimationDrawable 并知道动画何时结束

转载 作者:IT老高 更新时间:2023-10-28 22:10:31 31 4
gpt4 key购买 nike

我想用几个图像文件制作动画,为此 AnimationDrawable 效果很好。但是,我需要知道动画何时开始以及何时结束(即添加一个像 Animation.AnimationListener 这样的监听器)。搜索完答案后,我感觉 AnimationDrawable 不支持监听器..

有谁知道如何在 Android 上使用监听器创建逐帧图像动画?

最佳答案

在做了一些阅读之后,我想出了这个解决方案。我仍然很惊讶 AnimationDrawable 对象中没有监听器,但我不想来回传递回调,所以我创建了一个引发 的抽象类onAnimationFinish() 方法。我希望这对某人有所帮助。

自定义动画drawable类:

public abstract class CustomAnimationDrawableNew extends AnimationDrawable {

/** Handles the animation callback. */
Handler mAnimationHandler;

public CustomAnimationDrawableNew(AnimationDrawable aniDrawable) {
/* Add each frame to our animation drawable */
for (int i = 0; i < aniDrawable.getNumberOfFrames(); i++) {
this.addFrame(aniDrawable.getFrame(i), aniDrawable.getDuration(i));
}
}

@Override
public void start() {
super.start();
/*
* Call super.start() to call the base class start animation method.
* Then add a handler to call onAnimationFinish() when the total
* duration for the animation has passed
*/
mAnimationHandler = new Handler();
mAnimationHandler.post(new Runnable() {
@Override
public void run() {
onAnimationStart();
}
};
mAnimationHandler.postDelayed(new Runnable() {
@Override
public void run() {
onAnimationFinish();
}
}, getTotalDuration());

}

/**
* Gets the total duration of all frames.
*
* @return The total duration.
*/
public int getTotalDuration() {

int iDuration = 0;

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

return iDuration;
}

/**
* Called when the animation finishes.
*/
public abstract void onAnimationFinish();
/**
* Called when the animation starts.
*/
public abstract void onAnimationStart();
}

要使用这个类:

    ImageView iv = (ImageView) findViewById(R.id.iv_testing_testani);

iv.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {

// Pass our animation drawable to our custom drawable class
CustomAnimationDrawableNew cad = new CustomAnimationDrawableNew(
(AnimationDrawable) getResources().getDrawable(
R.drawable.anim_test)) {
@Override
void onAnimationStart() {
// Animation has started...
}

@Override
void onAnimationFinish() {
// Animation has finished...
}
};

// Set the views drawable to our custom drawable
v.setBackgroundDrawable(cad);

// Start the animation
cad.start();
}
});

关于Android AnimationDrawable 并知道动画何时结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214735/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com