In order to get a view to slowly fade in or out of view, use an ObjectAnimator
. As seen in the code below, set a duration using .setDuration(millis)
where the millis
parameter is the duration (in milliseconds) of the animation. In the below code, the views will fade in / out over 500 milliseconds, or 1/2 second. To start the ObjectAnimator
's animation, call .start()
. Once the animation is complete, onAnimationEnd(Animator animation)
is called. Here is a good place to set your view's visibility to View.GONE
or 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();
}