TextView animation - fade in, wait, fade out
protected AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f ) ;
protected AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
txtView.startAnimation(fadeIn);
txtView.startAnimation(fadeOut);
fadeIn.setDuration(1200);
fadeIn.setFillAfter(true);
fadeOut.setDuration(1200);
fadeOut.setFillAfter(true);
fadeOut.setStartOffset(4200+fadeIn.getStartOffset());
Works perfectly for white backgrounds. Otherwise, you need to switch values when you instantiate AlphaAnimation
class. Like this:
AlphaAnimation fadeIn = new AlphaAnimation( 1.0f , 0.0f );
AlphaAnimation fadeOut = new AlphaAnimation(0.0f , 1.0f );
This works with black background and white text color.
That's the solution that I've used in my project for looping fade-in/fade-out animation on TextViews:
private void setUpFadeAnimation(final TextView textView) {
// Start from 0.1f if you desire 90% fade animation
final Animation fadeIn = new AlphaAnimation(0.0f, 1.0f);
fadeIn.setDuration(1000);
fadeIn.setStartOffset(3000);
// End to 0.1f if you desire 90% fade animation
final Animation fadeOut = new AlphaAnimation(1.0f, 0.0f);
fadeOut.setDuration(1000);
fadeOut.setStartOffset(3000);
fadeIn.setAnimationListener(new Animation.AnimationListener(){
@Override
public void onAnimationEnd(Animation arg0) {
// start fadeOut when fadeIn ends (continue)
textView.startAnimation(fadeOut);
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationStart(Animation arg0) {
}
});
fadeOut.setAnimationListener(new Animation.AnimationListener(){
@Override
public void onAnimationEnd(Animation arg0) {
// start fadeIn when fadeOut ends (repeat)
textView.startAnimation(fadeIn);
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationStart(Animation arg0) {
}
});
textView.startAnimation(fadeOut);
}
Hope this could help!
Kotlin Extension functions for Guy Cothal's answer:
inline fun View.fadeIn(durationMillis: Long = 250) {
this.startAnimation(AlphaAnimation(0F, 1F).apply {
duration = durationMillis
fillAfter = true
})
}
inline fun View.fadeOut(durationMillis: Long = 250) {
this.startAnimation(AlphaAnimation(1F, 0F).apply {
duration = durationMillis
fillAfter = true
})
}
You can use an extra animation object (which doesn't modify its alpha) to prevent the instant fade out, set animationListener for your fade-in effect and start the extra animation object in the on animationEnd of the fade-in, then you start fade-out on animation end of the extra animation object, try the link below, it'll help..
Auto fade-effect for textview