简体   繁体   中英

Android making a button fade in and out continuously

I am trying to get a button to fade in and out continuously and I cant seem to figure it out.

In the OnCreate:

Button playbtn =(Button) findViewById(R.id.playbutton);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.tween);
playbtn.startAnimation(myFadeInAnimation);

tween xml file:

 <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="1000"
        android:repeatMode="reverse"
        android:repeatCount="infinite" />
</set>

Thanks for your help.

You can do this:

private void fadeIn() {
    ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 0f, 1f);
    objectAnimator.setDuration(500L);
    objectAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            fadeOut();
        }
    });
    objectAnimator.start();
}

private void fadeOut() {
    ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f);
    objectAnimator.setDuration(500L);
    objectAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            fadeIn();
        }
    });
    objectAnimator.start();
}

You can improve by consolidating both methods into a single one by keeping track of the state (fading in, fading out). You should also add a function to cancel the animation (you can return the animator from these functions and then call cancel on it).

Edit: to cancel, you can do this - create a member variable that holds your current animator, then simply can cancel on it:

private ObjectAnimator objectAnimator;

private void fadeOut() {
    objectAnimator = ObjectAnimator.ofFloat(mButton, "alpha", 1f, 0f);
    objectAnimator.setDuration(500L);
    objectAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            fadeIn();
        }
    });
    objectAnimator.start();
}

private void cancelAnimator() {
    if (objectAnimator != null) {
        objectAnimator.cancel();
        objectAnimator = null;
    }
}

Your code works perfectly for me..

also you can do button fade in and out continuously in java Using

myFadeInAnimation .setRepeatCount(Animation.INFINITE); 

Hope this will helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM