ViewAnimator OnDraw throws NullPointerException if you remove child on onAnimationEnd

This is not a question, but rather as a communication with others, a problem that I faced and how I resolved it.
Basically, I was trying to create a ViewAnimator that would create additional children in response to user clicks.
To clean up after I revived the next view, I put

outAnimation.setAnimationListener(listener);

      

and in the AnimationListener

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

      

Now the problem with the above approach, just after onAnimationEnd, throws a NullPointerException. Basically, this means that the ViewAnimator is still using a child view that is being animated for drawing. Since I removed it there is null in there. I did my research and it basically looks like this is a known bug. See: Android Animation Not Completed onAnimationEnd

To fix this, I changed the layout.

<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>

      

and onAnimationEnd I can call safely container.removeAllViews()

. To animate the new view, I select the hidden container and

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

      

I would love to see your comments and advice.

+3


source to share


2 answers


I ran into this problem and used the view method post

to wait for the animation:



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

      

+4


source


I solved it. I have inAnimation and 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;

    }


}

      

+1


source







All Articles