Creating and using fragments

Jason Fedin
A free video tutorial from Jason Fedin
Instructor / Software Developer
4.4 instructor rating • 6 courses • 150,518 students

Learn more from the full course

The Essential Android O Developer Course (Java)

Learn everything in detail on how to write apps in Android O using Java

38:44:50 of on-demand video • Updated May 2020

  • Create and Run your first mobile application
  • Write Efficient and High Quality Android applications
  • Understand how to compile and test Android Applications using Android Studio
  • Learn all aspects of Android development from beginner topics to advanced
  • Learn how to Design and Implement Graphical User Interfaces in Android
  • Learn how to integrate databases into an android application to store persistent data
  • Learn how to submit apps to the Google Play Store and generate revenue with ads and in-app purchases
  • Learn about using Fragments for dynamic User Interfaces with multiple screen sizes
  • Understand how to implement mobile apps using the Java Programming Language
  • Learn Many more Android concepts!!!
English [Auto] All right welcome another exciting lecture about fragments in particular in this election will be talking about creating and using fragments in your activity. I am very enthusiastic about fragments because they're super cool technique that allows your user interfaces to be very dynamic and flexible. And again as I mentioned in previous lectures it's not just about getting the code to work it's about writing quality code and allowing for depth ability. So how do we use and how do we create fragments while fragment itself consist of the following. It has an X amount layout file this all all files just like an activities Exham all file contains all the components graphical elements and how they're displayed on the screen. All the properties widgets buttons whatever you want to call these controls and they essentially represent the screen. The difference with a fragment is that the fragment is just a portion of the screen or it could be a full screen but it's usually just a portion of the screen. Now you don't technically have to put all of your graphic elements in SML layout file although I strongly encourage it. Technically you could just define your graphics Kafka elements in Java source code but for the purpose of this class and this class I don't really allow that. You do not want to go that route by providing the graphic elements in X-amount file. You separate the content makes it much easier to maintain. This is what we want to do. We want to have our Rafidah elements in an X Somalia file. So whether it's a fragment or an activity you don't really know the difference. The only real way you would know that in the layout files representing a fragment is you're probably name layout file something like. My fragment the other part of fragment that you need to include is Java source code a Java class file. This is going to define the behavior of a fragment the way that you can identify a fragment Besides its name good by using good naming conventions is it will extend the fragment class. This again will have handle all the events and also structure the UI update any graphical controls things like that. Things that an activity does also to define a fragmented and XOMA file like I mentioned is no different than defining any other layout file contains graphical elements use layouts all the things that we've talked about in previous lectures to create a fragment and define its behavior you have to extend the fragment class or one of its subclasses. This is how you can identify that the Java class is a fragment. It's very similar to an activity. When we do our demonstration on converting an activity to a fragment we'll end up copying and pasting a lot of the code from resisting activity into the fragment class and just modifying it a bit removing some of the callbacks that are relevant and maybe doing some other things. So it's very similar to an activity. As I mentioned you don't have to just subclass the fragment class. You can also extend the dialog fragment list fragment or preference fragment will actually be doing this as well because in one of our activities we're going to convert to a fragment to contain a date picker in a time picker which are dialogue's. And if you have a date time date or time picker or any fragment you can't show it directly. You have to show it as a subclass of dialog fragment. So we'll be going this route when we do our demo. But as long as you extend one of these four classes you will be considered a fragment. You have to use the entry view callback to define the layout. This is the only required callback in the fragment lifecycle that you need to implement the concrete view draws all the graphical elements. It returns a view object while you'll do on the concrete view is you're going to inflate the X Somalia File. Up until this point we've all of our files we've always called like Sakata view on it. If you want to create a view object out of a file you have to call a method called inflate. And so it's a little different in fragments you're inflating next XML files as opposed to loading it in Sekhon time you know now as I mentioned earlier technically you don't have to use an X Somalia file you can do it in Java source code but we're not doing that just because you're required to implement the anchoring view. It doesn't mean you shouldn't neglect the other lifecycle callbacks. We know that you need to manage state you need your application to respond when a screen goes away when when you receive a phone call the activity disappears and things like that. You still have to manage that and the fragment class to respond to this state so you're going to be implementing other callbacks in your fragment class. You also want to make sure you use version for the support library the support libraries allow your application to run on older devices. And we're striving to have our application run on as many devices as possible. If you use vergence for support and the version for support fragment manager your application will run on more devices. There's also a version 7 support library but that runs on less devices so we're going to stick with version 4 so that we can support as many devices as possible reach as many users as we can for our applications. Here's an example of a fragment class that inflates Anax Amal al. What you should notice immediately is when you define the class you use the extends keyword to subclass fragment. So to identify that's a fragment you're going to see something like this or you're going to see an extended dialog fragment or one of the other subclasses of fragment. This is going to tell you it's a fragment you have to do this if you're implementing a fragment. The minimum requirements to implement a fragment is you have to have this override of the concrete view. The view is part of the fragments lifecycle that gets invoked when when you start to draw the graphical elements it takes three parameters to lay out inflator The View group in the bundle. What you'll usually see the concrete view is this inflator Daten flate method. And like I mentioned earlier because we can't load the SML and we're not in the concrete for an act we're not an activity we have to inflate it and inflate is is what it's doing is it's creating a view object from a nail file and you'll see this and other other techniques to do other things as well. But for the for the fragment we have to call inflate we pass it in our layout our layout file looks like any other layout file contains graphical elements and the layout of all those. The container is just the parent view group and then false we usually have the bottle saved since they set the false. In this case. So this is a very basic simple example of what a fragment class could look like. Now obviously it's going to have a lot more it's going to respond to other callbacks for state changes. You're going to have other logic in there for behavior to respond to events similar things that you have seen in previous activities now we know we need to understand how you can use a fragment How can an activity utilize a fragment for an activity doesn't use a fragment fragment is useless. So we need to understand this part of it to utilize a fragment. You can you can do this in two ways. The first way you utilize a fragment is you declare the fragment in the activities X Somali efile. So we know that most activities are going to load in some file and when they load that Somalia file they're going to do that in the Cancri method. It's no different with a fragment you're going to still load an X Somalia file. The only difference is that the Somalia file is going to not contain graphical components it's just going to contain the fragment. So you're going to see a fragment element inside the label file and it's going to point to the fragment that you want to load. And remember that in that illegal file can in activities like all file can have one fragment or many fragments. When you do it this way you're doing it. It's referred to as the static method. So you utilize this method when you do not plan to dynamically load any fragments. So if you have your X Somalia file and it has the fragment element inside of it you can not replace add or change any fragments at runtime. You would utilize this method when you're certain that your activity is going to contain these fragments one of more fragments and you're never going to change those fragments. What you'll do on the in the Somalia file inside the fragment element is you're going to set the Java class name through the name attribute or the class attribute depending on the version the API you have. This is going to point to the java source file for the fragment and then you're going to load it like any other activity in content view. You're going to refer to this XOMA lay out in the concrete method. Pretty basic there. Again the difference here is that the layout file that you're loading in your site view just contains one or more fragment element tags the other way to utilize a fragment and activity is to do in a more dynamic way. What you end up doing here is you have a supporting java file via the fragmentation in fragment transaction classes. You utilize these classes to dynamically add remove or swap elements. So if you have this idea that your activity is going to be changing a lot it's going to be changing the fragments that are displayed. You want to do this method and this method is going to basically not allow you to have the fragment tag inside of the Somali file in the XML file itself. What you have is as you'll have a placeholder like a frame layout that divides the screen into two or some variation of that and what you'll do is at runtime you'll use that placeholder to load in your fragments. You cannot have the fragment element if you want to dynamically remove or swap elements so I want to emphasize that. And we'll have some examples of this how we can get the fragment manager objects and call fragment transit transaction methods to add and remove. Again this is that dynamic method. So here is an example of the static method the static method where you have your layout file and it's very very small and depending on how many fragments you have this example just has one fragment inside of it. This is the same all layout file that you would load in your activity what you say you notice here is that fragment tag that fragment element and then the name and word call name is pointing to the java source file. So this package is com example and it fragments in your Java source files my fragment. You also need to have an android ID for your fragment and then some kind of different layouts depending on how you're going to display it. But you may have multiple fragment elements on here but if you have this method again you can't dynamically add or remove different fragments if you want to dynamically change the fragments at runtime. You have to do it programmatically. And so what you'll need to do is you only to use these fragment manager and fragment translation classes so you'll define the fragments for an activity in the Java source code itself. I mentioned you will have to use the Fragonard manager class to create fragment transactions. You'll get an instance of the frag manager and then call methods on private transactions. You also want to add default fragments and create a callback. So in the end create a callback after you call subcontext view to load your placeholder. You will then need to base. You will then need to get a fragment manager object and add a default fragment. If you didn't do that then it would you would base. You would come up and your activity would be blank. So always added the default fragment in the concrete. Your activity still needs that layoff. As I mentioned this is referred to as a placeholder but it's only a container it's just somewhere you can insert your fragment. It needs to be there. It's usually an empty frame layout. So it looks something like this. You have your activity then you just have a frame layout and what you do is you use the containers ID and you'll use that when you call in call the add method or the Remove method or the replace method. You'll use that ID to swap out or to add some more and add a fragment to this container but you need this at a minimum because you need to say where are you going to put the fragment. So to add in place or move to add remove replace or fragment you have to use the API and the fragment turns the transaction and you can only get a fragment transaction from the fragment manager. So this is the code you'll utilize to first get the fragment manager object and then using that fragment manager object your call a method called begin transaction which will return or fragment transaction. So these are the first steps you need to do when you start to dynamically add remove or replace a fragment. The next step would be to call your method whether it be and so forth and this example we're adding. So here we would create an instance of the fragment that's your Java source code fragment class and then you would call the add method on the fragment transaction object and you would pass in your container where you want to put the fragment and then the name of the fragment that you want to load. And when you're adding multiple fragments of the same container the order in which you add them determines the order they appear in the for you Hocker. So that's important order matters and how they show. The last thing you want to do none of this is going to matter unless you call the commit method the commit method. Well we'll do the operation will perform the operation. So for trend fragment transaction document will do the actual adding in this example. If you don't call that you're not going to add the fragment dynamically. And this always doesn't always happen immediately. There are some other helpers that you can call to move it up in the queue and so forth if you want to replace or move the fragment. It's very similar to just call different methods. So what you end up doing is in the previous example you'll call replace remove. The other thing that you want to do when you replace or remove is you may want to add user navigation to undo the change so when you have fragments any activity you can always hit that backbone when you hit that back. Backbite and when you're dynamically loading fragments it won't go to the preview screen unless you manage that. So what you need to do to manage the user pressing the back button when are utilizing fragments is you have to call this add tabac stack before you commit. And then you have to override a method called on back on back pressed to manage the fragments on the back stack. Again what would happen if you didn't implement this as you'd hit the backbone and you want to go to the back to the previous screen the previous fragment. And that's important because then the user could get lost and so forth. This is very easy to do and it's not very complicated. So here's an example. Again you would get the transaction from the support manager by calling begin transaction. This is one line compared to the multiple lines and the previous example. And then you would call your method on that transaction. So replace or remove again passing in the container and the new fragment that you want to replace or remove then you would call add to back stack so that if the user presses the back button you can manage it. And then lastly you can you call the commitment that method finalizes the transaction what's not showing here is that on back pressed over a method that manages the back stack. But that's pretty simple. So I also want to talk about fragment strategies when you utilize rackets We'll talk about this more as well when we talk about supporting multiple screen sizes. So if you remember this illustration in the right top right corner. This is a strategy to handle this. This is a typical use case where you have a tablet in a handset the tablet uses two fragments fragment and be in a master detail type of view whereas the handset handset you loads of fragment a Depending on what you select and drag may loads another activity for fragment B. You can actually implement this use case two different ways. So the first way is you could have multiple fragments in a single activity. You always have one activity. So even in the in the illustration where it says activity contains fragment a activity B can things fragment B. You don't have to do it that way. Activity it could contain fragment a and then dynamically activity could load fragment one fragment a as user event. So that's one strategy you could do. You could again display two fragments for tablet's display one fragment on a handset device and then swap in and out the fragments. But again what the point here is you always have one activity and you decide at runtime how to swap things or if it's a tablet you just need to show them the other strategy is to use multiple fragments multiple activities. And this is what the illustration is showing using multiple activities multiple fragments and the demonstration that I'm going to provide I'm going to do it both ways just to show you the differences. But really the preferred way is to do the second strategy multiple fragments multiple activities so an activity can include multiple different fragments for a certain configuration. If the detail fragment is there the main activity tells a fragment that it should just update itself. It loads to fragments when anything changes the fragment 8 updates fragment B if the detail fragment is not there the main activity starts another activity. So what you'll see here is multiple activities. You'll see things like I'm starting the activity starting an activity for result. Harvey you invoke an activity you don't see any dynamically swapping as much dynamically swapping. You still might see that but you have multiple activities this way is easier to manage in my opinion the multiple activities just. It also buys you a lot because you have separate activities you don't have to manage as much things the system will do more things for you as well. Miscellaneous things I want to talk about in order to get the fragment itself. You can call the fine fragment by the method used to get fragment manager. You should always use defragment defrag manager in this thing. In this illustration is correct. You can also call get fragments support manager but I think if you don't have an instance you have to call get fragment manager and this will be useful because sometimes you have to check a fragment is present in the layout. This is how you can tell whether or not you're on a tablet or whether on your phone. Many other ways as well but this is one way. So this is demonstrating that you can you can use to get fragment manager and call and look for a particular fragment and if the fragment is returned from the layout then you know that you need to start doing the activity that you're in a hands Hansa in if you're not if the fragments Nalls not in the layout. Then you can just up the fragen and be you also use the fine fragment by the for other manipulations that you need to do with the fragment if you need to get a particular instance of a fragment that was already loaded and you may need to operate on that you would also use find fragment Pietie or you can also use find fragment by tag when you create a fragment or for the frag manager itself. You can that don't a headless fragment for example you can pass the fragment manager a tag as opposed to an ID because you don't have a fragment ID if you don't have a user or you don't have a layout because you don't have any property so you would have to utilize the tag to find the correct fragment headless fragment fragments do not subclass the contex class. So what you'll see in a lot of the after the concrete method call back. You can't do it in the concrete because you don't have an activity yet. But in the on activity created what you'd need to do in order to get graphical elements is you'll need to call get activity to get the parent activity and then you can do a find find view by the so just keep that in mind some of the callbacks don't have the activity yet so you cannot get the user interface elements in the ones that do have an activity you have to call get activity to get the parent activity to pop fragments off the stack back on the stack. You can use the pop back stack method. This is in relation to hitting the key. You can register a listener for changes to the back stack with add on back stack change listener. And so lastly I wanted to talk about a fragment without a UI had less fragment you can use this thing Kapolei some state across configuration changes or for just a background processing task. My suggestion is you should really do this but it is available and there may be a need. I haven't had a need yet but there may be a need I will just use a service or some kind of other background processing activity. Android O has started limiting your background processing that you can do so this this might be a little more problematic with a headless fragment. What you would do is you would add the fragment to the activity using the add method. You're not in the activity how you usually utilize a fragment is you either create it the SML file statically or you dynamically load it through the fragment manager class and fragment transactions. You don't have that option if you have don't have a user interface. So what you do is you call the add method you pass in the fragment and the tag name to the frame Bregman manager class. So the tag is really the idea of the fragment. You don't have a view ID because you're not a at graphics alone adds fragment but not of you so you do not need to implement the on Preview method for headless fragments. There will be no callback for this and that's it. That's a lot of information. We'll definitely go through the process of doing this in code. So it makes more sense. But again writing in a lecture an overview will give you a head start so that when I go through the code you'll be able to follow it more. So thank you for listening.