I am trying to use a single instance of the same TextView to achieve the following fading animation effect (by setting textView.setText
):
.setText
is set to "Welcome" on initialize- Fade Out
.setText
to "How are you?"- Fade In
- Fade Out
.setText
to "How old are you?"- Fade In
- Fade Out
- And so on...
The effect is to fade new text in and then fade out. However I have tried many different ways, but can only achieve the above by using multiple TextView objects in the XML and Java class.
This is my current code:
textViewA.animate().alpha(1).setDuration(1000).setStartDelay(2000).withEndAction(new Runnable() {
@Override
public void run() {
textViewA.animate().alpha(0).setDuration(1000).setStartDelay(2000).start();
textViewB.setText("Next Question");
}
}).start();
}
Then I have to keep repeating the above code, by setting the second textViewB.setText
to the new text, then repeat the fading for each new textView
object (textViewA
, textViewB
, textViewC
, textViewD
).
How can I achieve this with a single TextView?
Note: I have tried to simply fade out the textView
, then use textView.setText
whilst alpha
is set to 0, then fade it back in to alpha
set to 1, but as soon as I call the textView.setText
method, the textView
overrides the fader and appears immediately.
CodePudding user response:
To use a single TextView for the fade in and fade out animation you have to create two different Runnable
End Actions
one for fadeInEndAction
and one for fadeOutEndAction
and from each Runnable get the correct ViewPropertyAnimator
to start the fade in or fade out.
Based on your example you can achieve this effect using a single TextView like below:
TextView tv;
String[] stringMessages = {"Welcome", "How are you?", "How old are you?"};
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tv = findViewById(R.id.textView);
setText();
getFadeOutViewPropertyAnimator().start();
}
private ViewPropertyAnimator getFadeInViewPropertyAnimator(){
return tv.animate().alpha(1).setDuration(1000).setStartDelay(2000).withEndAction(fadeInEndAction);
}
private ViewPropertyAnimator getFadeOutViewPropertyAnimator(){
return tv.animate().alpha(0).setDuration(1000).setStartDelay(2000).withEndAction(fadeOutEndAction);
}
private final Runnable fadeInEndAction = new Runnable() {
@Override
public void run() {
//no more strings to show stop the fade-in/out loop here
if(i == stringMessages.length){
return;
}
getFadeOutViewPropertyAnimator().start();
}
};
private final Runnable fadeOutEndAction = new Runnable() {
@Override
public void run() {
setText();
getFadeInViewPropertyAnimator().start();
}
};
private void setText(){
tv.setText(stringMessages[i ]);
}
Result: