Tuesday, 27 November 2012

Android: DialogFragment enter and exit animations

Adding enter and exit animations to your DialogFragment's dialog is a three-step process:
  1. define the enter and exit animations;
  2. add your animations to a style;
  3. set the style as your dialog's "window animations".
That's the gist of it. In greater detail, and assuming you want fade in and fade out animations, this is what you need to do.

First, define the animations. Add a fade_in_dialog.xml file to your res/anim folder which has the following xml code...

<?xml version="1.0" encoding="utf-8"?>
<alpha
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/accelerate_interpolator"
  android:fromAlpha="0.0"
  android:toAlpha="1.0"
  android:duration="400" />

And a fade_out_dialog.xml file to your res/anim folder which has the following xml code...

<?xml version="1.0" encoding="utf-8"?>
<alpha
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/decelerate_interpolator"
  android:fromAlpha="1.0"
  android:toAlpha="0.0"
  android:duration="400" />

Second, add a style to your res/styles.xml file defined as follows:

<style
  name="dialog_animation_fade" >
  <item name="android:windowEnterAnimation">@anim/fade_in_dialog</item>
  <item name="android:windowExitAnimation">@anim/fade_out_dialog</item>
</style>

Third (and final!), add the following code to your DialogFragment.onStart() method:

@Override
public void onStart() {
  super.onStart();

  // safety check
  if (getDialog() == null) {
    return;
  }

  // set the animations to use on showing and hiding the dialog
  getDialog().getWindow().setWindowAnimations(
      R.style.dialog_animation_fade);
  // alternative way of doing it
  //getDialog().getWindow().getAttributes().
  //    windowAnimations = R.style.dialog_animation_fade;

  // ... other stuff you want to do in your onStart() method
}

Done! Your dialogs should now fade in and fade out when shown and dismissed respectively.

6 comments:

Sergio Torres said...

Thank mate, I always end up at your blog

Sergio Torres said...
This comment has been removed by the author.
adil said...

Hey hey Sergio, you're most welcome :)

Unknown said...

Thank you!

Anonymous said...

I have an error with "getDialog()", saying that the method isn't defined. I'm sure I'm missing something simple, but how do I define it without breaking your animation?

Anonymous said...

how to add duration to animations