2015-04-02 123 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