Adding Animation on Dialog

Web Hosting
In this tutorial, I will show you how to add animation in your dialog. See sample below!

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
}


Web Hosting
Done! Your dialogs should now fade in and fade out when shown and dismissed respectively. That's it!

No comments:

Post a Comment