2015-04-02 59 views
5

當我在自定義視圖中運行此代碼時,onAnimationStartonAnimationEnd將不斷重複調用。這不奇怪嗎?作爲一名Android程序員,我希望他們分別只被調用一次。無法刪除ViewPropertyAnimator的監聽器

final ViewPropertyAnimator animator = animate().setDuration(1000).alpha(0.0f); 
    animator.setListener(new AnimatorListenerAdapter() { 
     @Override 
     public void onAnimationStart(Animator animation) { 
      Utils.log("----------------start"); 
     } 

     @Override 
     public void onAnimationEnd(Animator animation) { 
      Utils.log("--------- end"); 
     } 
    }).start(); 

但後來我試圖通過消除聽衆解決問題時onAnimationEnd得到通過的setListener(null)ViewPropertyAnimator調用,但它從來沒有工作,儘管什麼寫在文檔:

public ViewPropertyAnimator setListener (Animator.AnimatorListener listener) 

Added in API level 12 
Sets a listener for events in the underlying Animators that run the property animations. 

Parameters 
listener The listener to be called with AnimatorListener events. A value of null removes any existing listener. 
Returns 
This object, allowing calls to methods in this class to be chained. 

有沒有人遇到這個奇怪的問題?也許這是一個Android的錯誤?

+0

你在哪裏調用animator.start()? – pskink 2015-04-02 08:00:25

+0

在我的自定義視圖,順便說一句,其實,我想我甚至不需要調用它,動畫將由下一個機會(也許下一幀)開始。我在文檔 – Leo 2015-04-02 08:06:04

+0

的某個地方閱讀它「在我的自定義視圖中」是什麼?什麼方法? – pskink 2015-04-02 08:10:11

回答

18

我剛碰到這個問題,但沒有自定義視圖。

就我而言,我對同一視圖有兩個動畫。演出和隱藏。

所以這是

showView(){ 
    myView.animate().translationY(myView.getHeight()).setListener(new ...{ 
    ... 
    onAnimationEnd(Animation animation){ 
    hideView(); 
    } 
    ...}).start(); 
} 
hideView(){ 
    myView.animate().translationY(0).start(); 
} 

當hideView()完成後,它會再次調用本身。這是因爲老聽衆還在設置。修復它的關鍵在於在第二個動畫中將偵聽器設置爲null。例如

hideView(){ 
    myView.animate().translationY(0).setListener(null).start(); 
} 
+5

setListener(null)實際上可以從偵聽器回調本身中調用,這使得代碼更加整潔,因爲偵聽器自身清理完畢。 – 2015-04-25 21:25:26

+0

@SafaAlai如何? – Mauker 2016-04-20 21:48:14

+0

@Mauker你可以使用myView.animate()。setListener(null);在onAnimationEnd ..看起來有點奇怪,但看着android源代碼animate()方法返回以前創建的ViewPropertyAnimator,所以你只是獲取該值,並將偵聽器設置爲null。 – 2016-04-25 20:30:52