如何不取消 animate().alpha(1).setDuration(100)

How to not cancel the animate().alpha(1).setDuration(100)

我试图编写显示 ImageView 淡出然后淡出的代码,所以它出现在屏幕上然后消失,现在,我试过这个代码

banana.animate().alpha(1).setDuration(3000);
banana.animate().alpha(0).setDuration(3000);

现在你可以看到这两行正在淡出一个叫做 bananaImageView 应该需要大约 3 秒,然后在另外三秒后淡出,总共 6 秒动画,但它并没有这样做,而是第二行取消了第一行,使图像永远不会出现。

有没有可能让它毫无问题地出现和消失?

目前您正在尝试同时绘制它们。所以你需要一种回调或监听器来告诉你第一个动画已经完成,然后继续第二个。

banana.animate().alpha(1).setDuration(3000).setListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            banana.animate().alpha(0).setDuration(3000);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });

您可以使用 withEndAction:

banana.animate().alpha(1).setDuration(3000)
    .withEndAction(new Runnable() {

        @Override
        public void run() {
            banana.animate().alpha(0).setDuration(3000);
        }
    });

您可以改用自定义的 TimeInterpolator 来自动反转动画,这是我刚刚制作的:

import android.animation.TimeInterpolator;
import android.view.animation.LinearInterpolator;

/**
 * Maps time into another interpolator so that the animation plays, and then reverses.
 * i.e. time maps like so:
 * [0..0.5, 0.5..1] maps to [0..1, 1..0]
 */
public final class AutoReverseInterpolator implements TimeInterpolator {

    private final TimeInterpolator inner;

    /**
     * Decorator constructor, use if you don't want a linear interpolation.
     * @param inner
     */
    public AutoReverseInterpolator(TimeInterpolator inner) {
        this.inner = inner;
    }

    /**
     * Linear interpolation constructor.
     */
    public AutoReverseInterpolator() {
        this(new LinearInterpolator());
    }

    @Override
    public float getInterpolation(float input) {
        input *= 2;
        if (input > 1) {
            input = 2 - input;
        }
        return inner.getInterpolation(input);
    }
}

用法:

banana.animate().alpha(1).setDuration(6000)
      .setInterpolator(new AutoReverseInterpolatorDecorator());

或者对于更复杂的动画链,您应该考虑使用 xml 来定义动画或使用 AnimatorSet