Adding enter and exit animations to your
DialogFragment's
dialog is a three-step process:
- define the enter and exit animations;
- add your animations to a style;
- set the style as your dialog's "window animations".
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:
Thank mate, I always end up at your blog
Hey hey Sergio, you're most welcome :)
Thank you!
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?
how to add duration to animations
Post a Comment