3

I'm trying to animate the alpha of a button, which works well when I set the alpha from 1 to 0. However, at the final of the animation, I can't reset it from 0 to 1 because the button's alpha is already 1 (and this causes the button to just "jump" in the screen without any fade). It seems that the Animation object isn't setting the view alpha directly, but some presentation property of the view. Does anyone have an idea of how can I put this animation to work correctly?

My code:

private void performFavoriteButtonFade(boolean isFavorite) {
    AlphaAnimation fadeAnimation = new AlphaAnimation(0, 0);
    if (isFavorite) {
        if (this.favoriteButton.getAlpha() == 1) {
            fadeAnimation = new AlphaAnimation(1, 0);
        }
    } else {
        if (this.favoriteButton.getAlpha() == 0) {
            fadeAnimation = new AlphaAnimation(0, 1);
        } else {
            fadeAnimation = new AlphaAnimation(1, 1);
        }
    }

    fadeAnimation.setDuration(300);
    fadeAnimation.setFillAfter(true);

    this.favoriteButton.startAnimation(fadeAnimation);
    this.favoriteButton.setVisibility(View.VISIBLE);
}
<ImageButton
        android:id="@+id/favoriteButton"
        android:src="@drawable/favorite_icon"
        android:background="@android:color/transparent"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="30dp"
        android:layout_marginBottom="20dp"
        android:visibility="invisible"
        android:onClick="didTapNotFavorite"
        />

Notes:

I'm setting the view visibility because of the answer in this post to make the AlphaAnimation work properly.

Community
  • 1
  • 1
Tiago Maia
  • 616
  • 1
  • 6
  • 20

2 Answers2

6

You seem to be using the old style of animation. You can use the new style and it should work without changing visibility or filling after. Instead of setting the visiblility in your XML just set the alpha to 0.

Fade out:

Button button = new Button(mActivity);
button.animate().alpha(0).setDuration(300).start();

Fade In:

Button button = new Button(mActivity);
button.animate().alpha(1f).setDuration(300).start();
Adam W
  • 972
  • 9
  • 18
0

Try this:

AlphaAnimation fadeAnimation;
        if (isFavorite) {
            if (this.favoriteButton.getAlpha() == 1) {
                fadeAnimation = new AlphaAnimation(1, 0);
                fadeAnimation.setInterpolator(new AccelerateInterpolator());
            }
        } else {
            if (this.favoriteButton.getAlpha() == 0) {
                fadeAnimation = new AlphaAnimation(0, 1);
                fadeAnimation.setInterpolator(new DecelerateInterpolator());
            } else {
                fadeAnimation = new AlphaAnimation(1, 1);
            }
        }
GIGAMOLE
  • 1,274
  • 1
  • 11
  • 17