8

当我在自定义视图中运行此代码时,onAnimationStartonAnimationEnd不断被调用。这不是很奇怪吗?作为一名 Android 程序员,我希望它们分别只被调用一次。

    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();

但是后来我尝试通过在onAnimationEndViewPropertyAnimator's调用时删除侦听器来解决问题,setListener(null)但是尽管文档中写了,但它从未起作用:

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的错误?

4

1 回答 1

27

我刚刚遇到了这个问题,但没有自定义视图。

就我而言,我在同一个视图上有两个动画。一个显示和隐藏。

所以它是

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();
}
于 2015-04-23T23:43:26.763 回答