Skip to content Skip to sidebar Skip to footer

How To Apply A Fade-in/fade-out Animation When Replacing A Fragment

I am replacing a fragment with another fragment. I want the first fragment to disappear with a fade-out effect and second fragment to appear with fade-in effect. How is this done?

Solution 1:

With addition to @MD code

FragmentManagermanager= getSupportFragmentManager();
FragmentTransactionft= manager.beginTransaction();

ft.setCustomAnimations(R.anim.fade_in,
                R.anim.fade_out);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();

and When you Pop Fragment then apply animation like:

FragmentManagermanager= getSupportFragmentManager();
FragmentTransactionft= manager.beginTransaction();
ft.setCustomAnimations(R.anim.fade_out, R.anim.fade_in);

ft.replace(R.id.realtabcontent, fragment);      
ft.commit();

and XML for fadeIn

<setxmlns:android="http://schemas.android.com/apk/res/android"><alphaandroid:fromAlpha="0.0"android:toAlpha="1.0"android:duration="@android:integer/config_mediumAnimTime" /></set>

and XML for fadeOut

<setxmlns:android="http://schemas.android.com/apk/res/android"><alphaandroid:fromAlpha="1.0"android:toAlpha="0.0"android:duration="@android:integer/config_mediumAnimTime" /></set>

Solution 2:

When you Push a Fragment then apply animation like:

FragmentManagermanager= getSupportFragmentManager();
FragmentTransactionft= manager.beginTransaction();

ft.setCustomAnimations(R.anim.fade_in,
                R.anim.fade_out);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();

and When you Pop Fragment then apply animation like:

FragmentManagermanager= getSupportFragmentManager();
FragmentTransactionft= manager.beginTransaction();
ft.setCustomAnimations(R.anim.fade_out, R.anim.fade_in);

ft.replace(R.id.realtabcontent, fragment);      
ft.commit();

Hope this works for you.

Update: For more information go to

  1. http://android-er.blogspot.in/2013/04/implement-animation-in.html
  2. Animate the transition between fragments

Solution 3:

It is worth adding that setCustomAnimations can also have 4 arguments:

FragmentTransaction setCustomAnimations(int enter, 
                                         int exit, 
                                         int popEnter, 
                                         int popExit)

Set specific animation resources to run for the fragments that are entering and exiting in this transaction. The popEnter and popExit animations will be played for enter/exit operations specifically when popping the back stack.

Post a Comment for "How To Apply A Fade-in/fade-out Animation When Replacing A Fragment"