user1214739 user1214739 - 3 months ago 13
Android Question

TextView fade out and disappear

I have a

TextView
in my activity, I would like to show the text, then fade out and hide it completely whenever the activity is started.

I have a wired situation, my code sometimes working (the
TextView
is fade out and gone), but most of times, it is not working (it could not reach the
onAnimationEnd
function).

Here is my code for it:

protected void onResume() {
fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
fadeOut.setDuration(5000);
//fadeOut.setFillBefore(true);
fadeOut.setFillAfter(true);
//fadeOut.setStartOffset(1000);


fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
Log.d(TAG, "fade out start");
}

@Override
public void onAnimationEnd(Animation animation) {
Log.d(TAG, "fade out end");

textRotateHint.setVisibility(View.INVISIBLE);
}

@Override
public void onAnimationRepeat(Animation animation) {
Log.d(TAG, "fade out repeat");
}
});

textRotateHint.setVisibility(View.VISIBLE);
textRotateHint.setText(R.string.rotation_hint);
textRotateHint.startAnimation(fadeOut);

super.onResume();
}

Answer

You can use a simple value animator.

ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0f);
valueAnimator.setDuration(5000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float alpha = Float.parseFloat(animation.getAnimatedValue().toString());
        mTextView.setAlpha(alpha);
    }
});
valueAnimator.start();