结束动画事件

我在一个视图中有一个淡出动画(在一个片段中) ,每次动画发生时,在它完成后,视图再次重新绘制自己。我找到了一份做 view.SetVisibility(View.GONE)的工作。但它不等动画完成。只有在动画完成之后,我才想执行这个 setVisiability 代码。最好的方法是什么?

79517 次浏览

You can add Animation listener to your animation object like

anim.setAnimationListener(new Animation.AnimationListener(){
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
}
});

You can also achieve this using Animation.setFillAfter

Simply take your animation object and add animation listener to it. Here is the example code :

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**




}
});

Functionally the same as the accepted answer but in a much more concise way:

// Add/Remove any animation parameter
theView.animate()
.alpha(0)
.setDuration(2000)
.withEndAction(new Runnable() {
@Override
public void run() {
theView.setVisibility(View.GONE);
}
});

Enjoy :)

Example for 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
}
})