Tuesday, May 3, 2016

Dialog Animations in Android

Been working on a project for my client. A value add implementation of  dialog sliding from bottom to middle of screen literally made my day. Too good not to share and so here it goes. For, confidentiality,i'm not sharing the screen shot. But, i can assure you that this code will smooth glide into your layouts and class file elements.

Here is my pusedo code:
1. Create dialog layout and position it over but at bottom of parent screen.
2. The dialog needs to smoothly glide from bottom to middle of the screen.

Here is how it is done:
1. Create a anim folder in res (res/anim).
2. Create two animation resources
2a. Slide_up_dialog
<pre class="brush: csharp">
xml version="1.0" encoding="utf-8"?> <
set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate       
      android:duration="@android:integer/config_mediumAnimTime"     
       android:fromYDelta="0%p"       
    android:interpolator="@android:anim/accelerate_interpolator"     
     android:toXDelta="0" /> 
</set>
</pre>
2a. Slide_up_dialog
<pre class="brush: csharp">

xml version="1.0" encoding="utf-8"?><
set xmlns:android="http://schemas.android.com/apk/res/android" >
 <translate      
    android:duration="@android:integer/config_mediumAnimTime"     
     android:fromYDelta="0%p"      
     android:interpolator="@android:anim/accelerate_interpolator"      
    android:toYDelta="25%p" />
</set>
</pre>
3. Create Style resources in Styles.xml
<pre class="brush: csharp">

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up_dialog</item>
    <item name="android:windowBackground">@null</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowNoTitle">true</item>
</style>
</pre>
4. Extend the DialogAnimation style into your DialogTheme Style (on Same Page)
<pre class="brush: csharp">
<style name="DialogSlideAnim" parent="@android:style/Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/DialogAnimation</item>
    <item name="android:windowExitAnimation">@anim/slide_out_down</item>
</style>
</pre>
4. Java Code for Animating XML elements of Dialog
<pre class="brush: csharp">
//First the Dialog object creation
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.calendar_dialog);
//Second implement the following code to implement the animation
Window window = dialog.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.windowAnimations = R.style.DialogAnimation;
//to keep the dialog window to the bottom of the parent screen
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
//Finally
dialog.show();
</pre>
Sit back and treat yourself for the dialog animation you've just created ;-)