How to replace a Fragment with another Fragment using custom animation

Are there any app in Google Playstore which does not contain fragments? Well, there may be. But, we are not talking about a static app. We are discussing about a full-fledged app. Every Android developer would know how important are fragments for an app. It allows us to reuse the code and we have a new lifecycle, full of hassles but with advantages as well.

This article is not about Fragments in detail but a simple scenario used in many app nowadays. We are going to see how can we replace that fragment with another fragment with a custom animation.


Do all the necessary setup for creating a new android project. Jump to MainAcitivity and add a in the activity’s layout. Put the id of as “@+id/fragment”. Let’s say the fragment you added is “FragmentA”. Create another fragment with name “FragmentB”.

We want custom animations. All the animations file should go under res/anim folder. By default, anim folder won’t be available in your project. For creating anim folder right click on res and select New -> Android Resource directory. From the “resource type” dropdown select anim and click OK.You’ll see the anim folder is now available under res directory.

For creating a file right click on anim folder and click on New-> Animation resource file. Name it as “slide_in.xml” and enter the following code in the file.


Create another animation file “slide_out.xml” and enter the following code.



Create a utility class “FragmentUtility” that extends Fragment class. Here, we ll create a static method for replacing FragmentA with FragmentB. The method takes an instance of FragmentManager, FragmentTransaction and Fragment class.

public class FragmentUtilityextends Fragment {

public static void replaceFragment(FragmentManager manager, FragmentTransaction transaction, Fragment fragment ){
transaction.setCustomAnimations(R.anim.slide_in, R.anim.slide_out);
transaction.replace(, fragment);

setCustomAnimations() method allows us to show animation while replacing a fragment. First argument is for the fragment which enters and the second argument is for the fragment which exits.

replace() method replaces its first argument with the second. First argument is the id the view in the xml. The second argument is the fragment which is going to replace the .

And lastly, commit the transaction using commit().


Inside MainActivity class, suppose the is showing the FragmentA’s layout and we want to replace it with FragmentB’s layout. We can achieve this by using static replaceFragment() method. Put this code inside a button click and see how FragmentA replaces FragmentB with slide animation.

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
FragmentReplace.replaceFragment(manager, transaction, new FragmentB());

admin Author

Leave a Reply

Your email address will not be published. Required fields are marked *