To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the FragmentManager
to create a FragmentTransaction
.
For a single FragmentTransaction
, there are two different ways to perform animations: you can use a standard animation or you can supply your own custom animations.
Standard animations are specified by calling FragmentTransaction.setTransition(int transit)
, and using one of the pre-defined constants available in the FragmentTransaction
class. At the time of writing, these constants are:
FragmentTransaction.TRANSIT_NONE
FragmentTransaction.TRANSIT_FRAGMENT_OPEN
FragmentTransaction.TRANSIT_FRAGMENT_CLOSE
FragmentTransaction.TRANSIT_FRAGMENT_FADE
The complete transaction might look something like this:
getSupportFragmentManager()
.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.contents, new MyFragment(), "MyFragmentTag")
.commit();
Custom animations are specified by calling either FragmentTransaction.setCustomAnimations(int enter, int exit)
or FragmentTransaction.setCustomAnimations(int enter, int exit, int popEnter, int popExit)
.
The enter
and exit
animations will be played for FragmentTransaction
s that do not involve popping fragments off of the back stack. The popEnter
and popExit
animations will be played when popping a fragment off of the back stack.
The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.contents, new MyFragment(), "MyFragmentTag")
.commit();
The XML animation definitions would use the objectAnimator
tag. An example of slide_in_left.xml might look something like this:
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="x"
android:valueType="floatType"
android:valueFrom="-1280"
android:valueTo="0"
android:duration="500"/>
</set>