Android Fragments and Fragments Lifecycle

What is fragmentation?

Android Fragments:- Fragment is a UI fragment that can be embedded in the activity, it can make the program more reasonable and sufficient Utilize the space of the large screen, so it is widely used on the tablet. Although fragmentation should be a brand new concept to you Read, I believe you should have no effort to learn, because it is so similar to activities, it can also contain layout, It also has its own life cycle. You can even understand the fragments as a mini activity, although these mini Activities may be as big as normal activities.

So how to use the fragments to make full use of the space of the tablet screen? Imagine we are developing a News application, one of the interfaces uses ListView to display a set of news headlines. When one of the headlines is clicked, Open another interface to display the detailed content of the news. If it is designed in a mobile phone, we can put the news headline list in one activity, but the details of the news in another activity, as shown in Figure1.

Android Fragments

However, if you design the same on the tablet, the news headline list will be stretched to fill the entire tablet The title of the news is generally not too long, which will result in a lot of blank areas on the interface, as shown in Figure2.

Android Fragments

Therefore, a better design solution is to put the news headline list interface and the news detailed content interface in two pieces respectively Then, the two fragments are introduced in the same activity so that the screen space can be fully utilized, as shown in the figure As shown in figure3.

Android Fragments

How to use Android fragments:

Having introduced so many abstract things, it is time to learn the specific usage of fragments. You already know, broken Tablets are usually used in tablet development, so the first thing we have to do is to create a new tablet simulation Device. Since there seems to be a bug in the tablet simulator of the 4.0 system, here I will create a new tablet simulator of the figure2 system, such as shown in Figure 4.4.

Android Fragments

Now start the tablet simulator, the effect is shown in Figure 4.5

android fragments

Ok, the preparations are complete, then create a new FragmentTest project, and then start our fragment exploration Take a trip.

Simple usage of Android Fragments:

Here we are going to write a simple example of Android Fragments to practice hands, add two Android Fragments in an activity, and Let these two fragments divide the activity space equally. Create a new left_fragment.xml layout, the code is as follows:

This layout is very simple, just place a button and make it horizontally centered. Then create a new fragment layout on the right right_fragment.xml, the code is as follows:

As you can see, we set the background color of this layout to green and placed a TextView to display a Paragraph text. Then create a LeftFragment class, inherited from Fragment. Note that there may be two different packages The Fragment below is for you to choose, it is recommended to use, because our program is for Android 4.0 For the above system, the Fragment under another package is mainly used to be compatible with the lower version of the Android system. LeftFragment The code is as follows:

Here is just to rewrite Fragment’s onCreateView() method, and then pass LayoutInflater in this method The inflate() method dynamically loads the left_fragment layout just defined, the whole method is simple and clear. Then We use the same method to create a new RightFragment, the code is as follows:

Basically, the code is the same, I believe there is no need to explain it. Next, modify activity_main.xml The code in is as follows:

As you can see, we used the <fragment> tag to add Android Fragments to the layout, and most of the attributes you specify It is familiar, but here you need to explicitly specify the name of the fragment class to be added through the android:name attribute. Note one Be sure to add the package name of the class. So the simplest fragment example has been written, now run the program, the effect is shown in Figure6.


As we expected, the two Android Fragments equally divided the layout of the entire event. But this example is too simple It’s hard to have any practical role in a real project, so let’s take a look at the more advanced skills.

Dynamically add Android Fragments:

In the previous section, you have learned how to add Android Fragments to the layout file, but the real power of Android Fragments The point is that it can be dynamically added to the activity while the program is running. Add  Android Fragments dynamically according to the specific situation, you can The program interface can be customized more diversified. We continue to improve on the basis of the above code  and create another_right_fragment.xml, the code is as follows Shown:

The code of this layout file is basically the same as the code in right_fragment.xml, except that the background color is changed to yellow Color and changed the displayed text. Then create another RightFragment as another right fragment, the code is as shown below:

The code is also very simple, the another_right_fragment just created is loaded in the onCreateView() method layout. So we have prepared another fragment, let’s look at how to dynamically add it to the activity. Repair Change activity_main.xml, the code is as follows:

As you can see, the Android Fragments on the right are now placed in a FrameLayout. Remember this layout? In the previous chapter As we have learned, this is the simplest layout in Android. It does not have any positioning method. All controls will be Placed in the upper left corner of the layout. Since only one fragment needs to be placed in the layout, it is very suitable for use FrameLayout. Later, we will replace the content in FrameLayout in the code to realize the function of dynamically adding Android Fragments. Modify The code in MainActivity is as follows:

As you can see, first we register a click event for the button in the left fragment, and then dynamically add the fragment The logic is placed in the click event. Combining the code, it can be seen that dynamically adding Android Fragments is divided into 5 steps.

  1. Create a fragment instance to be added.
  2. Get the FragmentManager, which can be obtained by directly calling the getFragmentManager() method in the activity.
  3. To start a transaction, start it by calling the beginTransaction() method.
  4. Adding Android Fragments to the container is generally implemented using the replace() method. You need to pass in the id of the container and the fragments to be added Instances.
  5. Commit the transaction and call the commit() method to complete.

This completes the function of dynamically adding Android Fragments to the activity. Re-run the program and you can see the same boundary as before. Then click the button, the effect is shown in Figure7.

Android Fragments

Simulate the return stack in the fragment:

In the previous section, we successfully implemented the function of dynamically adding Android Fragments to the activity, but if you try it, it will be posted Now, after adding a fragment by clicking the button, the program will exit directly by pressing the Back key. If here We want to imitate the effect similar to the return stack, press the Back key to return to the previous fragment, how to achieve it? It’s actually very simple. FragmentTransaction provides an addToBackStack() method that can be used to add a transaction to the return stack, modify the code in MainActivity, as shown below:

Here we call the addToBackStack() method of FragmentTransaction before the transaction is committed, it can Receive a name to describe the status of the return stack, generally null can be passed in. Now re-run the program and click the button Add AnotherRightFragment to the activity, and then press the Back key, you will find that the program does not exist, but After returning to the RightFragment interface, press the Back key again to exit the program.

Communication between Android Fragments and activities:

Although the Android Fragments are displayed embedded in the activity, in fact, their relationship is not so close. You can watch Out, fragments and activities exist in a separate category, and there is no obvious way between them. Connect to communicate. If you want to call the method in the fragment in the activity or call the method in the activity in the fragment, you should How to achieve it?

In order to facilitate communication between Android Fragments and activities, FragmentManager provides a similar to findViewById() The method, specifically used to obtain fragment instances from the layout file, code is as follows:

RightFragment rightFragment = (RightFragment) getFragmentManager() .findFragmentById(;

By calling the findFragmentById() method of FragmentManager, you can get an instance of the corresponding fragment in the activity, Then you can easily call the method in the fragment. Knowing how to call the method in the fragment in the activity, how to call the method in the activity in the fragment? Its In fact, this is even simpler. In each fragment, you can get the association with the current fragment by calling the getActivity() method. The activity example, the code is as follows:

MainActivity activity = (MainActivity) getActivity();

With the activity instance, it becomes easy to call the method in the activity in the fragment. Also when needed in fragments When using the Context object, you can also use the getActivity() method, because the obtained activity itself is a Context Object.

At this time, I don’t know if you will have a question in your mind. Since the communication problem between Android Fragments and activities has been solved, So is it possible to communicate between fragments and fragments?

To be honest, this problem is not as complicated as it seems. Its basic idea is very simple. First of all, in a fragment You can get the activity associated with it, and then use this activity to get another instance of the fragment. The communication function between different fragments is now available, so our answer here is yes.

Life Cycle of Android Fragments:

Like activities, Android Fragments have their own life cycle, and it is too similar to the life cycle of activities. Believe you will learn it soon, let’s take a look at it right away.

Fragment status and callback

Remember how many states each activity might have during its life cycle? Yes, there are running status and pause There are four states: state, stop state, and destruction state. Similarly, each shard may also experience these types during its life cycle. State, but there will be some differences in some small places.

  1. Running status

When a shard is visible and its associated activities are running, the shard is also running status.

  1. Suspended state

When an activity enters the paused state (because another activity that does not fill the screen is added to the top of the stack), and Its associated visible fragments will enter a suspended state.

  1. Stop state

When an activity enters the stopped state, the Android Fragments associated with it will enter the stopped state. Or by adjusting Use the remove() and replace() methods of FragmentTransaction to remove fragments from the activity, but there are Call the addToBackStack() method before handing in. At this time, the Android Fragments will also enter the stopped state. In general, enter The fragments in the stopped state are completely invisible to the user and may be recycled by the system.

  1. Destroyed status

Android Fragments always exist depending on the activity, so when the activity is destroyed, the fragments associated with it will enter To the destroyed state. Or by calling the remove() and replace() methods of FragmentTransaction to remove fragments from live It is removed during the move, but the addToBackStack() method is not called before the transaction is committed. At this time, the fragments will also enter To the destroyed state. Combining the previous activity state, I believe it should be effortless for you to understand it.

Similarly, the Fragment class also provides A series of callback methods are used to cover every link in the fragment life cycle. Among them, the callback methods and Android Fragments in the activity Almost all of them, but Android Fragments also provide some additional callback methods, so let’s focus on these callbacks.

  1. onAttach()

Called when the fragment is associated with the activity.

  1. onCreateView()

Called when creating a view for the fragment (loading the layout).

  1. onActivityCreated()

It is called when the activity associated with the shard must have been created.

  1. onDestroyView()

Called when the view associated with the fragment is removed.

  1. onDetach()

Called when the fragment is disassociated from the activity.

For the complete life cycle diagram of the fragment, please refer to Figure 8, which is from the official Android website.

Android Fragments

Experience the life cycle of Android Fragments:

In order to let you experience the life cycle of Android Fragments more intuitively, let’s practice it through an example. Example The sub is very simple, still modified on the basis of the FragmentTest project. Modify the code in RightFragment as follows:

We added the code to print the log in each callback method in Right Fragment, and then re-run Program, now observe the print information in LogCat, as shown in Figure 9.

Android Fragments

As you can see, when RightFragment is loaded on the screen for the first time, it will execute onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart() and onResume() methods. then click The button in LeftFragment, the print information at this time is shown in Figure10.

Android Fragments

Because AnotherRightFragment replaced RightFragment, RightFragment at this time entered a stop state

Therefore, the onPause(), onStop(), and onDestroyView() methods will be executed. Of course, if you didn’t replace it Call the addToBackStack() method, at this time the RightFragment will enter the destruction state, onDestroy() and The onDetach() method will be executed. Then press the Back key, RightFragment will return to the screen, and the print information is shown in Figure11.

Android Fragments

Since RightFragment has returned to the running state, onActivityCreated(), onStart() and The onResume() method will be executed. Note that at this time the onCreate() and onCreateView() methods will not be executed because We use the addToBackStack() method to make RightFragment and its view not destroyed. Press the Back key again to exit the program, and the print information is shown in Figure12.

Android Fragments

The onPause(), onStop(), onDestroyView(), onDestroy() and onDetach() methods will be executed in sequence, and the most

Eventually, destroy the activity and debris together. You have experienced the complete life cycle of fragments like this, do you have a deeper understanding? Engraved?

It is also worth mentioning that you can also save data in the fragment through the onSaveInstanceState() method. Because the Android Fragments that enter the stopped state may be recovered when the system memory is insufficient. The saved data is in You can retrieve all three methods of onCreate(), onCreateView() and onActivityCreated(), they all contain There is a savedInstanceState parameter of Bundle type.

Related Article:

Android ListView

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: