淡出動畫

為了使檢視慢慢淡入或淡出檢視,請使用 ObjectAnimator。如下面的程式碼所示,使用 .setDuration(millis) 設定持續時間,其中 millis 引數是動畫的持續時間(以毫秒為單位)。在下面的程式碼中,檢視將在 500 毫秒或 1/2 秒內淡入/淡出。要啟動 ObjectAnimator 的動畫,請致電 .start()。一旦動畫完成,就會呼叫 onAnimationEnd(Animator animation)。這是一個設定檢視對 View.GONEView.VISIBLE 的可見性的好地方。

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;

void fadeOutAnimation(View viewToFadeOut) {
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(viewToFadeOut, "alpha", 1f, 0f);

    fadeOut.setDuration(500);
    fadeOut.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            // We wanna set the view to GONE, after it's fade out. so it actually disappear from the layout & don't take up space.
            viewToFadeOut.setVisibility(View.GONE);
        }
    });

    fadeOut.start();
}

void fadeInAnimation(View viewToFadeIn) {
    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(viewToFadeIn, "alpha", 0f, 1f);
    fadeIn.setDuration(500);

    fadeIn.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStar(Animator animation) {
            // We wanna set the view to VISIBLE, but with alpha 0. So it appear invisible in the layout.
            viewToFadeIn.setVisibility(View.VISIBLE);
            viewToFadeIn.setAlpha(0);
        }
    });

    fadeIn.start();
}