我在一个视图(位于片段内)中有一个淡入淡出的动画,每次动画完成后,该视图都会重新绘制自己。我发现周围有工作view.SetVisibility(View.GONE)
。但是,它不会等待动画完成。我只想在动画完成后执行此setVisibility代码。最好的方法是什么?
Answers:
您可以将Animation侦听器添加到动画对象,例如
anim.setAnimationListener(new Animation.AnimationListener(){
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
}
});
if (!anim.hasStarted() || anim.hasEnded())
来检测动画是否仍在运行。
在功能上与接受的答案相同,但更为简洁:
/* Add/Remove any animation parameter */
theView.animate().alpha(0).setDuration(2000).withEndAction(new Runnable() {
@Override
public void run() {
theView.setVisibility(View.GONE);
}
});
请享用 :)
.withEndAction(() -> theView.setVisibility(View.GONE));
您也可以使用Animation.setFillAfter实现此目的
只需将您的动画对象添加到动画对象中即可。这是示例代码:
rotateAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
**// WRITE HERE WHATEVER YOU WANT ON THE COMPLETION OF THE ANIMATION**
}
});
Kotlin示例
var fadeOutImage = findViewById<ImageView>(R.id.fade_out_Image)
val fadeOutAnimation = R.anim.fade_out_animation
val animation = AnimationUtils.loadAnimation(this, fadeOutAnimation)
fadeOutImage.startAnimation(animation)
animation.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
// not implemented
}
override fun onAnimationRepeat(p0: Animation?) {
// not implemented
}
override fun onAnimationEnd(p0: Animation?) {
fadeOutImage.visibility = View.INVISIBLE
}
})
fade_out_Image.animate().alpha(0f).setDuration(100L).withEndAction {fade_out_Image.visibility = View.GONE}.start()