淡出动画
为了使视图慢慢淡入或淡出视图,请使用 ObjectAnimator
。如下面的代码所示,使用 .setDuration(millis)
设置持续时间,其中 millis
参数是动画的持续时间(以毫秒为单位)。在下面的代码中,视图将在 500 毫秒或 1/2 秒内淡入/淡出。要启动 ObjectAnimator
的动画,请致电 .start()
。一旦动画完成,就会调用 onAnimationEnd(Animator animation)
。这是一个设置视图对 View.GONE
或 View.VISIBLE
的可见性的好地方。
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
void fadeOutAnimation(View viewToFadeOut) {
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(viewToFadeOut, "alpha", 1f, 0f);
fadeOut.setDuration(500);
fadeOut.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// We wanna set the view to GONE, after it's fade out. so it actually disappear from the layout & don't take up space.
viewToFadeOut.setVisibility(View.GONE);
}
});
fadeOut.start();
}
void fadeInAnimation(View viewToFadeIn) {
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(viewToFadeIn, "alpha", 0f, 1f);
fadeIn.setDuration(500);
fadeIn.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStar(Animator animation) {
// We wanna set the view to VISIBLE, but with alpha 0. So it appear invisible in the layout.
viewToFadeIn.setVisibility(View.VISIBLE);
viewToFadeIn.setAlpha(0);
}
});
fadeIn.start();
}