Android屬性動畫—Property Animation(五)

用AnimatorSet類來編排多個動畫

在很多場景中,一個動畫的播放要依賴與另一個動畫的開始或結束。Android系統讓你把這些相互依賴的動畫綁定到一個AnimatorSet對象中,以便能夠指定它們是同時的、順序的、或在指定的延時之後來播放。AnimatorSet對象也能夠彼此嵌套。

以下示例代碼來自Bouncing Balls示例,它按照以下方式播放Animator對象:

1.  播放bounceAnim

2.  同時播放squashAnim1、squashAnim2、stretchAnim1和stetchAnim2

3.  播放bounceBackAnim

4.  播放fadeAnim

AnimatorSet bouncer = new AnimatorSet();

bouncer.play(bounceAnim).before(squashAnim1);

bouncer.play(squashAnim1).with(squashAnim2);

bouncer.play(squashAnim1).with(stretchAnim1);

bouncer.play(squashAnim1).with(stretchAnim2);

bouncer.play(bounceBackAnim).after(stretchAnim2);

ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);

fadeAnim.setDuration(250);

AnimatorSet animatorSet = new AnimatorSet();

animatorSet.play(bouncer).before(fadeAnim);

animatorSet.start();

關於如何使用動畫集的完整示例,請看APIDemo中的Bouncing Balls示例。

動畫監聽器

使用下列介紹的監聽器能夠監聽動畫播放期間的重要事件:

1.  Animator.AnimatorListener

onAnimationStart()—動畫開始的時候被調用

onAnimationEnd()—動畫結束的時候被調用,它不管動畫是如何結束的。

onAnimationRepeate()—動畫重復播放的時候被調用

onAnimationCancel()—動畫被取消播放的時候被調用。

2.  ValueAnimator.AnimatorUpdateListener

onAnimationUpdate()—在動畫的幀上調用這個方法。通過監聽這個事件,使用在動畫期間由ValueAnimator對象產生的計算值。要使用這個值,就要用getAnimateValue()方法查詢傳遞到事件中的ValueAnimator對象,以便獲得當前的動畫值。如果使用ValueAnimator類,那麼實現這個監聽器是必須的。

根據屬性或對象的動畫效果,可能需要調用View對象上的invalidate()方法,用新的動畫值來強制屏幕的指定區域進行重繪。例如,Drawable對象的顏色屬性的動畫效果,在對象重繪自己的時候,隻會導致屏幕的更新。在View對象上的所有屬性的設置器,如setAlpha()、setTranslationX()等方法都會正確的讓View對象失效,因此在調用這些方法設置新值的時候,你不需要讓該View對象失效。

如果不實現Animator.AnimatorListener接口的所有方法,你能夠繼承AnimatorListenerAdapter類,來代替對Animator.AnimatorListener接口的實現。AnimatorListenerAdapter類對這些方法提供瞭空的實現,你可以選擇性的重寫這些方法。

例如,APIDemo中的Bouncing Balls示例就隻創建瞭一個AnimatorListenerdapter類的onAnimationEnd()回調方法:

ValueAnimatorAnimator fadeAnim =ObjectAnimator.ofFloat(newBall,"alpha",1f,0f);fadeAnim.setDuration(250);fadeAnim.addListener(newAnimatorListenerAdapter(){publicvoid onAnimationEnd(Animator animation){    balls.remove(((ObjectAnimator)animation).getTarget());}

 作者:FireOfStar
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *