TextView animation - fade in, wait, fade out

2019-03-15 01:10发布

问题:

I am making a picture gallery app. I current have a imageview with a text view at the bottom. Currently it is just semitransparent. I want to make it fade in, wait 3 second, then fade out 90%. Bringing focus to it or loading a new pic will make it repeat the cycle. I have read thru a dozen pages and have tried a few things, no success. All I get is a fade in and instant fade out

回答1:

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



回答2:

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.



回答3:

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!