Fade inout animation
suggest changeTo fade a view, use an ObjectAnimator. setDuration takes the length in milliseconds. The samples below fade over 500 milliseconds. Call start() to run the animator. Set the view to View.GONE in onAnimationEnd after a fade-out. Set it to View.VISIBLE in onAnimationStart before a fade-in.
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
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) {
// After the fade-out, GONE removes the view from layout.
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 onAnimationStart(Animator animation) {
// Make the view VISIBLE at alpha 0 so the fade-in has a place in the layout.
viewToFadeIn.setVisibility(View.VISIBLE);
viewToFadeIn.setAlpha(0);
}
});
fadeIn.start();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents