AlphaAnimation对象为什么不会改变被动画视图的alpha属性?

3
我正在尝试给一个按钮设置 alpha 动画,从 1 到 0 的过程中它能正常工作。然而,在动画结束时,我无法将其从 0 重置为 1,因为按钮的 alpha 已经是 1 了(这会导致按钮在屏幕上只是“跳”而不是渐变)。似乎 Animation 对象并没有直接设置视图的 alpha,而是设置了视图的一些演示属性。有人知道如何让这个动画正确工作吗?
我的代码:
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"
        />

注意:

我设置视图可见性是因为这篇文章中的答案,以使AlphaAnimation正常工作。

2个回答

6

您似乎正在使用旧式动画。您可以使用新样式,而无需更改可见性或填充后即可正常工作。只需在XML中设置alpha为0,而不是设置可见性。

淡出:

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

淡入:

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

0
尝试这个:
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);
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接