2017-03-16 427 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

相关问题