如果在onAnimationEnd上删除child,ViewAnimator的OnDraw会抛出NullPointerException

时间:2012-04-02 21:52:42

标签: android nullpointerexception viewanimator

这不是一个问题,更像是与他人分享我遇到的问题以及我是如何解决的。
基本上,我正在尝试创建一个ViewAnimator,他会根据用户点击次数创建额外的子项 在我为下一个View设置动画后进行清理,我把

outAnimation.setAnimationListener(listener);

并在AnimationListener中

public void onAnimationEnd(Animation animation) {
    viewAnimator.removeView(out);
}

现在,上面方法的问题是,在onAnimationEnd之后,它会抛出一个NullPointerException。基本上,这意味着,ViewAnimator仍在使用正在动画绘制的子视图。因为我删除了它,那里有空。 我做了我的研究,基本上,这似乎是一个已知的错误。请参阅:Android Animation is not finished on onAnimationEnd

为了解决这个问题,我修改了布局。

<ViewAnimator
    android:id="@+id/animator"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <FrameLayout
        android:id="@+id/container1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </FrameLayout>

    <FrameLayout
        android:id="@+id/container2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </FrameLayout>
</ViewAnimator>

和onAnimationEnd我可以安全地拨打container.removeAllViews()。要为新视图设置动画,我选择隐藏的容器和

container.addView(newView);
animator.setDisplayedChild(animator.indexOfChild(container));

我很乐意看到您的意见和建议。

2 个答案:

答案 0 :(得分:4)

我遇到了这个问题并使用了视图的post方法来等待动画真的完成:

      public void onAnimationEnd(Animation animation) {
        //Wait until the container has finished rendering to remove the items.
        view.post(new Runnable() {
          @Override
          public void run() {
            //remove view here
          }
        });
      }

答案 1 :(得分:1)

我解决了。我有inAnimation和outAnimation。 SO:

@Override
public void onAnimationEnd(Animation animation) {

    if(animationsFinished < 2) animationsFinished++;
    else{

        this.setInAnimation(null);  // Skipping this will cause trouble
        this.setOutAnimation(null); // Skipping this will cause trouble

        flipper.post(new Runnable(){

            @Override
            public void run() {
                flipper.removeView(previous);
            }

        });

        animationsFinished = 0;

    }


}
相关问题