Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make text fade in and out in Android?

I have a paragraph of text and when a button is clicked I want that text to fade out, change to some other text, then fade back in. I have some code but it doesn't do the fade out animation just the fade in.

    final TextView mSwitcher = (TextView) findViewById(R.id.bookContent);     mSwitcher.setText("old text");      final Animation in = new AlphaAnimation(0.0f, 1.0f);     in.setDuration(3000);      final Animation out = new AlphaAnimation(1.0f, 0.0f);     out.setDuration(3000);      Button moveOn = (Button) findViewById(R.id.moveOn);     moveOn.setOnClickListener( new OnClickListener() {         public void onClick(View v) {              mSwitcher.startAnimation(out);             mSwitcher.setText("new text");             mSwitcher.startAnimation(in);          }     }); 
like image 652
Andy Lobel Avatar asked Dec 24 '11 22:12

Andy Lobel


People also ask

What is fade in and fade out in Android?

In android, Fade In and Fade Out animations are used to change the appearance and behavior of the objects over a particular interval of time. The Fade In and Fade Out animations will provide a better look and feel for our applications.


1 Answers

You seem to be setting the animation to in right after you had set it to out. This makes only the "in" animation work.

To make the second animation start right after the first, you can add a listener to your first animation:

out.setAnimationListener(new AnimationListener() {      @Override     public void onAnimationEnd(Animation animation) {         mSwitcher.setText("New Text");         mSwitcher.startAnimation(in);      } }); 

Then, in your onClick() method:

public void onClick(View v) {      mSwitcher.startAnimation(out);  } 

That should do the trick.


Another approach is to use AnimationSet.

final Animation in = new AlphaAnimation(0.0f, 1.0f); in.setDuration(3000);  final Animation out = new AlphaAnimation(1.0f, 0.0f); out.setDuration(3000);  AnimationSet as = new AnimationSet(true); as.addAnimation(out); in.setStartOffset(3000); as.addAnimation(in); 

Then, instead of starting out, start as.

I hope this helps!

like image 136
eboix Avatar answered Oct 03 '22 10:10

eboix