2017-03-16 429 views
1

我不明白爲什麼這段代碼不能按預期工作。我想取消動畫。爲了測試它,我打電話給setLoading(true);誰開始動畫,立即致電setLoading(false);誰取消動畫。爲什麼Animation.cancel()和View.clearAnimation()在我的情況下不起作用?

代碼來測試它:

setLoading(true); 
setLoading(false); 

下面的代碼:

private void setLoading(boolean loading) { 
     if (loading) { 
      Animation animation = AnimationUtils.loadAnimation(this, R.anim.fade_out); 
      animation.setAnimationListener(new Animation.AnimationListener() { 
       @Override 
       public void onAnimationStart(Animation animation) { 
        Log.i(TAG, "start"); // for debug 
       } 

       @Override 
       public void onAnimationEnd(Animation animation) { 
        Log.i(TAG, "end"); // for debug 
        mButton.setVisibility(View.INVISIBLE); 
       } 

       @Override 
       public void onAnimationRepeat(Animation animation) { 

       } 
      }); 
      mButton.startAnimation(animation); 
      mLoading.setVisibility(View.VISIBLE); 
     } else { 
      Log.i(TAG, "cancel"); // for debug 
      mButton.getAnimation().cancel(); 
      mButton.setVisibility(View.VISIBLE); 
     } 
    } 

fade_out.xml:

<alpha xmlns:android="http://schemas.android.com/apk/res/android" 
    android:duration="500" 
    android:fromAlpha="1.0" 
    android:startOffset="300" 
    android:toAlpha="0.0" /> 

的logcat的:

start 
cancel 
end 

預期結果:

start 
cancel 

爲什麼onAnimationEnd()之後被稱爲Animation.cancel()View.clearAnimation()

我嘗試使用Animation.cancel(),使用View.clearAnimation()並使用兩者。

在此先感謝

回答

1

它的工作如預期,從Animatoin源代碼:

public void cancel() { 
    if (mStarted && !mEnded) { 
     fireAnimationEnd(); 
     mEnded = true; 
     guard.close(); 
    } 
    // Make sure we move the animation to the end 
    mStartTime = Long.MIN_VALUE; 
    mMore = mOneMoreTime = false; 
} 

private void fireAnimationEnd() { 
    if (mListener != null) { 
     if (mListenerHandler == null) mListener.onAnimationEnd(this); 
     else mListenerHandler.postAtFrontOfQueue(mOnEnd); 
    } 
} 

您可以檢查它是否是從內部onAnimationEnd

animation.getStartTime() == Long.MIN_VALUE 

動畫實際上已經取消這種方式此方法:

但它是私人的。時間是不同的,因爲在cancel()裏面你可以看到時間設置爲Long.MIN_VALUE

+0

那麼我怎樣才能取消動畫?或者如果動畫被取消,我可以在onAnimationEnd()中檢查? – MarcGV

+0

它的工作原理。你能推薦一個更好的方法嗎?或解釋動畫被取消時爲什麼StartTime不同?謝謝 – MarcGV

+0

我想不出更好的辦法,但我更新了答案,你可以看到爲什麼開始時間有這個值 – lelloman

相關問題