Replacing the Fragment in an Activity with Another Fragment

Start course
1h 33m

This course explores fragment operators in Kotlin. You'll learn about the different types of fragments and how you can use them.

Learning Objectives

  • Understand the basics of fragments, including where and why we use them
  • Learn how to create them
  • Learn how to change fragments inside an activity with another fragment
  • Learn about fragment backtrack, list fragments, and dialog fragments

Intended Audience

This course is intended for anyone who wants to learn how to start building their own apps on Android.


To get the most out of this course, you should have some basic knowledge of the fundamentals of Android.


So, what happens if you want to change fragments in the activity? Well, here we are. In this video, we're going to learn that: how to change a fragment inside the activity and add another fragment instead of it. So, pay attention. This is very important. Because when we talked about the advantages of fragments, talked about that you can pass one fragment to another fragment without closing the activity. So, here's how to do it. This is the video devoted to that. Enough of this small talk. Let's get into Android Studio. So, the project from the previous video, you see that it's open, and we'll just continue with that project. Now, we've already added a fragment to the main activity. So, now we're going to add a button. So, when we click on that button, one fragment will be close, and another fragment will be open.

So, we'll add this button to the design area, the MainActivity. So, here in the design area, there's a FrameLayout and the ConstraintLayout and, of course, you remember that we showed our fragment in the FrameLayout. So, now I will add a button just above the FrameLayout. Now, before we go into that, I do want to convert the ConstraintLayout to LinearLayout. You can still use the ConstraintLayout, but since it's going to be a simple design, it's just going to be easier to use the LinearLayout. And I'm just doing this replacement process on the xml side. So, I'll write LinearLayout instead of ConstraintLayout. Also, the orientation of LinearLayout, well, that will be vertical. We can also delete constraint values of the FrameLayout component because we no longer need constraint values. So, now let's move on to the design part. So, I'm going to drag a button from the palette and just drop it right above the frame layout in the Component Tree. And we'll change some properties of the button. So, I want to write here Replace Second Fragment to the text of the button here. So, when I click on that button, I want the second fragment to open. So, I'll adjust the width of the button to be wrap_content. Now, I'm going to center the button on the horizontal plane. To center the button on the design area, just adjust the gravity property of LinearLayout to center_horizontal. So, now I've got to put some space in between the button and the fragment. Don't you think? So, I'll change the layout margin value here. I'll adjust the layout_margin values to be 10dp. So, that will put 10dp space around the button. So, by opening the application, the first fragment; it's going to be added.

You saw that in action, right? That's the code that we wrote before. So, we're going to write the necessary code to open the new fragment when we click on the button. So, to be able to do that, that means I got to give an id to the button. I'm just going to write in buttonReplace for its id; that way, I'll remember exactly what's happening. Now, let's create the second fragment, which is going to be added. So, if you want to, why don't we just create the second fragment manually this time? What? You can do that? Absolutely. This way, you'll just know how to create the fragment yourself. Now, you remember back, we needed a design file and a Kotlin class for the fragment. So, why don't we just create the design file first? I'll open up the project directory, and we will create the design file in the layout folder under the res folder. I'll right click on the 'layout' folder with mouse, and I'll choose 'New', 'Layout Resource File' from the pop-up menu. Are you with me?

So, I got to give a name to the design file. So, I don't know; I'm going to call it second_fragment. But please, don't use capital letters and spaces when you're naming your file. Sorry to yell. So, when you click on the 'OK' button, the design file gets created for us. And that's cool. So, that's the design file created. So, now we need a Kotlin class. To create a new Kotlin class, again, from the project director. I'll right click on the project package folder, choose 'New', 'Kotlin Class/File' from the pop-up menu that opens. So, from here, just make sure the 'Class' option is selected. Now, we can give a name to the class, and I'm going to call it SecondFragment. So, the first letter of class names, did you see that before we go on any further? The first letter of class names is capitalized. These are the naming conventions. I'm not making it up. Also, if it consists of two different words, well, the first letter of the second word is also capitalized.

So, of course, yes. These are general naming conventions. Camel case, whatever you want to call it. But our new class is now created just by pressing the 'Enter' key on the keyboard. So, now we've got to convert this class to a fragment class. So, for this, well, it's got to inherit from the fragment class predefined by Android. So, we use the colon sign to inherit from a class in common. So after colon, I'll write Fragment and select the Fragment which comes from the androidx library,  and press 'Enter'. So, now this class is a Fragment class. Now, let's define the design file that we just created in this class. So, we'll do this in the onCreateView function, which is one of the fragment lifecycle methods. So here, I'll just type onCreateView, and press 'Enter'. Now, did you notice this function is a function that returns a View? So, we need to return a View. Well, here we will return the design that we made using the return keyword here. So, I'm deleting the statements here, and now I'll just type inflater.inflate. Thanks to this inflate method. We can define the design that we have here, and the inflate method will take three parameters. The first parameter is layout design we made. So, here I am writing (R.layout.second_fragment,) and the second and third parameters are fixed. So, the second parameter will be the container, which is the object of the ViewGroup class here, and the third parameter will also be false.

Okay, my friends, our fragment class is ready to go, so check it out though. You've learned how to create fragments in two different ways. Just let that sink in for a second. So, now we can continue with fragment replacement, which of course is our main topic, but that was just too good of a detour to pass up.

So, gather yourselves. And here, I will open the second_fragment.xml file. So, we will need to make a simple design. Because when we press a button, we need to understand that the second fragment is open. So, the design I'm going to make here will be the same as the first fragment design. So, I'm just going to open the design file of the first fragment, and I will copy all the XML code here, and I'm copying. So, now we're going to paste these codes that we copied into the design file of the second fragment. So, now let's try to distinguish one design from the other by just making a few changes. So, I want to write My Second Fragment for the text of the TextView. And that way, there's going to be no way to miss that it's the second fragment. I want to change the background of the second fragment. Yes, not really a great color, but you can, of course, choose whatever color you want. I just don't want to lose any time by sitting around choosing colors. So, there's the second fragment. So, what I need to do is write the necessary code in the MainActivity.

So, I'll define the button in the MainActivity. Here, I will write lateinit var replace : Button, then I'll match the button with its id in the onCreate method and I'll write replace = fineViewById( So, now I'll just add a ClickListener to that button. And I'm going to make the process of calling the second fragment from inside these curly brackets. So, I'll create an object from the fragmentManager class. After the val keyword, I'll give a different name to the second object because I already created an object in the name of the fragmentManager. So, I'll just write in here secondFragmentManager as the name of the new object. Now, after the equal sign, I'll write supportFragmentManager, and then I will create an object from the fragmentTransaction class and start the process of the transaction. So, I'll write val secondFragmentTransaction : FragmentTransaction  = secondFragmentManager.beginTransaction(). So then, I'll just create an object from the secondFragment class. So, I'll write val secondFragment = SecondFragment(), then I will write secondFragmentTransaction.replace(). So here, the replace method will run the new fragment. You follow? So, in other words, the first fragment will be closed, and the second fragment will be open. Just like that. So, this replaced method gets two parameters. First one is the idea of the layout which will show the fragment inside. So, I must define the frame layout with its id. So, here I'll write (,). The second parameter is the name of the second fragment, which is secondFragment. And for the third, I will close the process of the transaction. So, I'll write secondFragmentTransaction.commit(). So, as you can see, the process of changing the second fragment to the first fragment is, well, it's similar to the process of adding a new fragment, but we'll just use the replace method instead of the add method. So first, let's run the application and have a look. So, it's open. Now the first fragment's running. So, I'm going to click the button, and the second fragment starts to run. So, there you go. That is how to add a new fragment instead of just dumping the old fragment. So, I want to take a short break here. That's enough for this video. I want to see in the next one though because we got more to do.


About the Author
Learning Paths

Mehmet graduated from the Electrical & Electronics Engineering Department of the Turkish Military Academy in 2014 and then worked in the Turkish Armed Forces for four years. Later, he decided to become an instructor to share what he knew about programming with his students. He’s currently an Android instructor, is married, and has a daughter.

Covered Topics