Android 移除视图不会结束其动画

Android Removing View do not ends its animation

我在 RelativeLayout 中添加了带有 ObjectAnimator 的 childView。现在,当我从 RelativeLayout 中删除所有子项时,我仍然会触发 onAnimationEnd

一旦我从 RelativeLayout 中删除了所有子视图,我将如何停止所有子视图的动画。

RelativeLayout container = (RelativeLayout) findViewById(R.id.container);

RelativeLayout.LayoutParams layoutParams = getCircleLayoutParam(R.dimen.game_circle_width, R.dimen.game_circle_ht);

container.addView(view, layoutParams);

ObjectAnimator scale = ObjectAnimator.ofPropertyValuesHolder(view,
        PropertyValuesHolder.ofFloat("alpha", 0f),
        PropertyValuesHolder.ofFloat("scaleY", 1f),
        PropertyValuesHolder.ofFloat("y", 0, mWindowHeight));

scale.setDuration(SPEED_TIME);
scale.start();

scale.addListener(new Animator.AnimatorListener() {
    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        //Getting triggered even after calling container.removeAllViews()
    }

    @Override
    public void onAnimationCancel(Animator animation) {
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
    }
});

btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (scale != null){
                            scale.removeAllListeners();
                            scale.cancel();
                            scale.end();
                        }

                        container.removeAllViews();
                        container.invalidate();
                    }
                });

点击按钮调用 container.removeAllViews()container.invalidate()。我仍然 onAnimationEnd() 被触发。

非常感谢任何回复。

在通话前使用 removeAllListeners() or removeListener(Animator.AnimatorListener listener)

向容器添加 View 时,将 Animator 作为标记传递:

view.setTag(scale);

OnClickListener

btn.setOnClickListener(new View.OnClickListener() {

     @Override
     public void onClick(View v) {

         for (int i = 0; i < container.getChildCount(); i++)
         {
             View v = container.getChildAt(i);
             Object o = v.getTag();
             if (o != null && o instanceof ObjectAnimator)
             {
                 ((ObjectAnimator)o).cancel();
                 // or ...end(), see below
             }
         }
         container.removeAllViews();
         container.invalidate();
     }
});

使用 ValueAnimator.cancel()ValueAnimator.end() 取决于您想要达到的结果,参见 documentation

如果标签已被用于其他目的,可以保留一个包含 ObjectAnimator 的列表,并在 for 循环 运行 中遍历该列表。