无法删除ViewPropertyAnimator的侦听器

Leo*_*Leo 7 android viewpropertyanimator

当我跑我的自定义视图里面的代码,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();
Run Code Online (Sandbox Code Playgroud)

但后来我尝试通过在onAnimationEndViewPropertyAnimators 调用时删除监听器来解决问题,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.
Run Code Online (Sandbox Code Playgroud)

有没有其他人遇到这个奇怪的问题?也许这是Android的错误?

Jon*_*ock 22

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

就我而言,我在同一视图中有两个动画.表演和隐藏.

就是这样

showView(){
  myView.animate().translationY(myView.getHeight()).setListener(new ...{
    ...
    onAnimationEnd(Animation animation){
     hideView();
    }
    ...}).start();
}
hideView(){
  myView.animate().translationY(0).start();
}
Run Code Online (Sandbox Code Playgroud)

当hideView()完成时,它会再次调用自己.这是因为旧听众仍在设定中.修复它的关键最后是在第二个动画中将侦听器设置为null.例如

hideView(){
  myView.animate().translationY(0).setListener(null).start();
}
Run Code Online (Sandbox Code Playgroud)

  • setListener(null)实际上可以从侦听器回调本身中调用,这使得代码更加整洁,从那时起侦听器就会自行清理. (5认同)