How to animate fragment removal

hugoc picture hugoc · Dec 21, 2012 · Viewed 25.2k times · Source

I want to animate the removal of fragment.

I tried:

getSupportFragmentManager().beginTransaction()
    .setCustomAnimations(R.anim.push_down_in, R.anim.push_up_out)
    .remove(myFragment)
    .commit();

but the fragment just disappears.

I noticed the out animation only plays with 'replace', so I tried to replace the fragment with an empty Fragment like this:

getSupportFragmentManager()
    .beginTransaction()
    .setCustomAnimations(R.anim.push_down_in, R.anim.push_up_out)
    .replace(viewId, new Fragment())
.commit();

But it still just disappears disappears.

So, how can I animate the removal of fragment?

Answer

hugoc picture hugoc · Dec 22, 2012

I figured it out.

The exiting view is animated on the canvas of the entering view so if there is no entering canvas there is no canvas for the animation.

To show the animation I had to always use replace and use entering fragments of the same size to those exiting. After the animation is finished I set the view of the new fragments to gone.