Q: What about the Fragment lifecycle?
Fragments are added to Android after Android3.0+, but before Android does not have Fragments. Only one Activity can fit on a screen. This is an origin time when you introduce it. (PS: splinters for screen fit reasons)
Fragments profile
When learning fragments, you can associate them with previously learned activities because they have many similarities: they can contain layouts, have their own life cycles, and fragments can look like mini-activities. Fragment, as its name suggests, is designed to solve Android fragmentation. It can be used as part of the Activity interface, and can be dynamically added, removed, and exchanged during the Activity. Multiple fragments can exist in an Activity at the same time, and a Fragment can be used in multiple activities.
An Activity represents the body of a screen, and a Fragment can be a component of an Activity. An Activity can have several (0 or N) fragments. You can think of a Fragment as a control in an Activity, except that it is more closely related to an Activity than a normal control. As the Activity’s life cycle changes, the Fragment also has different life-cycle functions. Fragment is equivalent to a sub-activity in function. It can put multiple activities on the same screen, which means the reuse of user interface and functions. For large-screen devices, pure activities are not enough.
2.Fragment lifecycle
Take a look at the picture of the Fragment life cycle provided by the official documentation.
It can be seen from the figure above that the life cycles of fragments and activities are very similar. It can be said that the general life cycles are basically the same. Now I just need to introduce a few new methods that are not covered in the Activity.
OnAttach (): called when the Fragment is associated with the Activity
OnCreateView () : called when the Fragment creates a view
OnActivityCreated (): called when the Activity associated with the Fragment completes onCreate()
OnDestoryView (): called when the layout in the Fragment is removed
OnDetach (): called when the Fragment and Activity are unassociated
So we can roughly judge the periodic screen according to the Activity’s periodic method
(1) When opening the page
onCreate -> onCreateView -> onActivityCreated -> onStart -> onResume
Copy the code
(2) Press the home button
onPause -> onStop
Copy the code
(3) Open the interface again
onStart -> onResume
Copy the code
(4) Press the back button
onPause -> onStop -> onDestroyView -> onDestroy -> onDetach
Copy the code
The order in which methods are called under various variations of the Fragment loaded into the Activity is even more noteworthy. It should be noted that the FragmentManager of an Activity is responsible for calling the Fragment lifecycle methods on the queue. As long as the Fragment state is in sync with the Activity state, The FragmentManager that hosts the Activity continues to call other lifecycle methods to keep the Fragment state consistent with that of the Activity.
Attention attention attention
When an Activity joins a Fragment
(1) Open the interface
Fragment onCreate() -> Fragment onCreateView() -> Activity onCreate() -> Fragment onActivityCreated() -> Activity onStart() -> Fragment onStart() -> Activity onResume() -> Fragment onResume()
(2) Press the home button
Fragment onPause() -> Activity onPause() -> Fragment onStop() -> Activity onStop()
(3) Open the interface again
Activity onRestart() -> onActivity start() -> Fragment onStart() -> Activity onResume() -> Fragment onResume()
(4) Press the back button to exit
Fragment onPause() -> Activity onPause() -> Fragment onStop() -> Activity onStop() -> Fragment onDestroyView() -> Fragment onDestroy() -> Fragment onDetach() -> Activity onDestroy()
A key difference between the Fragment life cycle and the Activity life cycle is that the Fragment life cycle methods are invoked by the hosting Activity rather than the operating system. This is confirmed by the fact that Activity lifecycle methods are protected and fragments are public, since the Activity needs to call those Fragment methods and manage them.
Load the Fragment method
Now let’s learn how to load a Fragment in an Activity
(1) Static loading: Declare a Fragment in a layout file that hosts the Activity
The process of static loading Fragment can be divided into four steps:
I will give you a demo below to give you a taste of the following (PS: be sure to write it yourself, the feeling is really different from the look, it will give you muscle memory).
First: create a new frag_layout. XML layout. This is the Fragment layout where only one TextView and Button are displayed.
Second: create a new MyFragment class and inherit the Fragment class, which references the package under V4 and is compatible. By the way, normally we import packages with v4 or V7 packages, here packages are backward compatible, otherwise unexpected problems may occur. We override the onCreateView() method here, which loads the newly defined Frag_layout into the View through the LayoutInflate () method, and returns that View.
Third: Modify in the main_XML layout, use the < fragment > tag to add fragments, and remember to add the Android :name attribute. An automatic prompt will follow, and the full form of the load is the package name. The name of the class
Step 4: Load the Main layout in MainActivity. Now that the MyFragment is statically loaded into the MainActivity, the controls in the fragment are naturally part of the activity. You can get the Button instance directly from the activity to register the click event.
Take a look at the results:
Second: Dynamic loading: Hosted activities are added dynamically through code
The dynamically loaded code is also very simple, just look at the example. Modify main. XML and delete the entire < fragment >. But it still keeps a LinerLayout space and gives the Id. Why do you do that? Reveal it now.
Next add a few lines of code to MainActivity:
The whole process can be roughly divided into three steps:
The first step is to get a FragmentManager object with the getFragmentManager() method and then an instance of FragmentTransaction with its beginTransaction().
The second step is to add the MyFragemnt instance to the Main LinearLayout using the beginTransaction. Add () method. Note that the first parameter in the add() method is the container view resource Id, not layout. The container view resource Id serves two purposes: it tells the FragmentManager where the shard view should appear in the active view; It is also the unique identifier of the fragment in the FragmentManager queue. The unique identifier for statically loaded fragments is the ID under < fragment> in the active layout.
Step 3: Call beginTransaction. Commit () to commit. Alternatively, if the user is allowed to return to the previous Fragment state by pressing the return key, call the addToBackStack(true) method before calling commit().
FindViewById: findViewById: findViewById: findViewById: findViewById: findViewById: findViewById: findViewById
Communication between Fragments and activities
An instance of the fragment can be obtained by calling the findFragmentById() method of the FragmentManager during the activity, and the methods in the fragment can then be called. Using the example above, if you want an example of a statically loaded fragment, add the following code to MainActivity:
MyFragment myFragment = (MyFragment) getFragmentManager(). findFragmentById(R.id.fragment);
Copy the code
To get an instance of a dynamically loaded shard, the code looks like this:
MyFragment myFragment = (MyFragment)fragmentManager(). findFragmentById(R.id.layout);
Copy the code
You can also get the activity instance associated with the current fragment by calling the getActivity() method in the fragment, making it easy to call the methods in the activity. For example, if you want to get an instance of MainActivity in MyFragment:
MainActivity activity = (MainActivity)getActivity();
Copy the code
Debris and activity could then easily communicate. Think about how fragments communicate with each other. The activity associated with one shard can be obtained first, and then the instance of another shard can be obtained through this activity, thus realizing the communication between different shards.
As long as we can have normal use.
As far as I am concerned, there is usually an Activity with several fragments in a normal APP, so we need to implement it through an adapter. After implementation, the corresponding operations of each Fragment are still implemented in its own Fragment. Not in an Activity.