Category: C #, Android, VS2015;
Date Created: 2016-02-22 I. INTRODUCTION
Android has introduced the concept of fragment from 3.0, primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because the tablet screen is much larger than the phone screen, there is more room to assemble and swap the UI components.
Perhaps you can understand it faster: compared to WPF, if you think of activity as a window or page similar to WPF, then fragments's role is similar to the one or more frame elements that WPF contains in window or page.
This section describes each of the following:
- How to use fragment to create an Android application, including how to maintain its state when adding fragment to the background stack;
- How to share events with multiple fragment that belong to the activity in the same activity;
- How to build multiple fragment into an activity's action bar;
Wait a minute. Ii. Basic Concepts
Fragment shows a behavior or part of the behavior of the user interface in activity. You can combine multiple fragment into a multi-region UI on a single activity, and can be reused across multiple activity. Fragment can be thought of as a module component of activity that has its own lifecycle, receives its own input events, and can be added or deleted while the activity is running.
1. Fragment must be embedded in an activity to be able to use
Fragment must be embedded in an activity to be used, and the life cycle of the fragment is directly affected by the life cycle of its host activity.
For example, once an activity is paused, all of its fragment are suspended, and once an activity is destroyed, all of its fragment will be destroyed. However, when activity is running (in the life cycle state of resumed), you can manipulate each fragment individually, such as adding or removing a fragment. When you perform such a transaction, you can add it to a background stack, which is managed by the activity, each of the background stack content entities inside the--activity is a transaction record that fragment occurred. This background stack allows the user to rollback an fragment transaction by pressing the "Back" key (navigating backwards).
2, the role of fragment is to separate the layout of the activity into a number of parts
When you split the activity's layout into several fragment, you can control the rendering of the activity at run time, and those changes will be saved in the background stack managed by the activity.
For example, the news app puts a fragment on the left to display a list of articles, and a second fragment on the right to display an article, when two fragment are in the same activity, and each fragment has its own lifecycle callback method sequence, Used to process individual user input events. As a result, users can select and read articles in the same activity instead of selecting articles in one activity and reading them in another activity.
3. Can refer to the same fragment in multiple activity
Each fragment should be designed as a modular and reusable activity component. That is, you can reference the same fragment in more than one activity, because fragment defines its own layout and uses its own lifecycle callback behavior. This is especially important, the principle is simple, modularity and multiplexing allows you to change the fragment combination to meet different screen sizes.
When designing applications that support both tablets and phones, the fragments can be reused with different layout configurations. For example, on a mobile phone, when the same activity cannot accommodate more fragment, it may be necessary to provide a single-area interface by separating the fragments.
For example, in the case of a news application, you can embed two fragment in activity a when the program is running on a flat screen device. However, when running on the phone screen, there is not enough space to accommodate two fragment at the same time, so activity A can only refer to the fragment that contains the list of articles, and when the user selects one of the article titles, it can start activity B, It contains the second fragment for reading the article. In this way, the application can be reused by combining different fragments so that it can support both tablets and phones.
When a fragment is used as part of an activity layout, it exists within the viewgroup of the Activity View system and defines its own view layout. You can insert a fragment into the activity's layout with the <fragment> element in the activity layout file, or add it to an existing viewgroup in C # code. However, fragment does not have to be shown in the activity layout, and it can also work in stealth within the activity. Three, basic usage
The fragments has its own independent life cycle, as shown in:
1. Callback method thrown when creating a fragment
The callback method that is thrown when creating a fragment is described below.
(1) infalate () "Common"
Infalate: Inflatable expansion filling, which is the meaning of filling the width and height of fill.
When you create a fragment, you can override Oncreateview (), return a layout by Oncreateview (), and then populate it (inflate) into the XML (or axml) layout file. To make it easier for you to do this, Oncreateview () provides a Layoutinflater object.
For example, here is a fragment subclass whose layout is loaded from Example_fragment.xml:
public static Class Examplefragment:fragment
{
public override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate)
{
Fill fragment (inflate) into the layout
Return Inflater.inflate (Resources.layout.example_fragment, container, false);
}
}
The parameter of the incoming Oncreateview () container is the parent viewgroup (from the activity's layout) to which your frament layout will be inserted. If fragment is in the resumed state (the recovery state will be discussed more in the manipulation Fragment life cycle), the parameter savedinstancestate is an instance of the bundle class that provides data about the previous instance of fragment.
The inflate () method requires the following 3 parameters:
- The ID of the layout resource to populate (inflate).
- The parent viewgroup of the filled layout. It is important to pass in container in order for the system to apply layout parameters to the root view of the inflate layout, specified by the parent view that will be embedded.
- A Boolean value that indicates whether the layout that was infalte during inflate should be appended with ViewGroup (the second parameter). (False is passed in this example because the system has inserted the inflate layout into the container container--passing in true creates an extra viewgroup in the final layout).
Once you have created fragment, you can add this fragment to your activity.
(2) Onattach ()
This method is called when fragment is associated with an activity. This is the first method to run when fragment is ready.
In general, do not override the fragments default constructor and do not implement a new constructor for it. This is because in the Onattach () method, any component required by fragments may be reinitialized, which may result in the work done in the constructor being invalidated.
(3) OnCreate () "Common"
After executing Onattach (), the system will then call the OnCreate () method. In the implementation code that overrides this method, you can initialize the necessary components that you want to keep in fragment, and then re-enable them when the fragment is paused or stopped.
When the system calls the OnCreate () method, the hierarchy view of the host activity may not be fully instantiated, so fragment should no longer rely on any part of the active view hierarchy in this method. For example, do not perform any adjustments to the UI or application in this method.
OnCreate () is the earliest time fragment began to collect the required data. At this point the fragment is running on the UI thread, so you should avoid any lengthy processing, and if the run time is really long, consider performing the processing on the background thread.
If the Setretaininstance (True) method is called, this method may be skipped. The workaround will be described in more detail later.
(4) Oncreateview ()
This method is called by the system when OnCreate () is finished to draw the user interface for fragment. This method needs to return the view used by the fragment. If fragment does not have a user interface, NULL is returned.
(5) onactivitycreated ()
This method is called when OnCreate () is completed and managed by the activity (or hosted into the activity). This is the last method to be executed before the fragment is adjusted to the user interface.
(6) OnStart ()
This method is called by the system when the included activity is restored, at which point the fragment is visible to the user. In many cases, the fragment will contain the code it should execute, or include the code it should execute in the activity's OnStart () method.
(7) Onresume ()
This is the last method that the user can call before interacting with the fragment. For example, enable features such as camera devices, location services, and so on in this method. However, as these services can cause battery consumption to be very fast, it is generally necessary to minimize the use of such applications to prolong battery life.
2. Callback method thrown when destroying a fragment
The following describes the callback method that is thrown when a fragment is destroyed.
(1) OnPause () "Common"
When OnPause () is called, the user will no longer be able to interact with the fragment. This is the case because some other fragment operations have modified this fragment, or the managed activity (hosting activities) has been paused. At this point, the activity that hosts this fragment is likely to still be visible, such as when the focus activity is partially transparent or the fragment does not occupy the entire screen.
When this method is activated, it is the first omen that the user leaves the fragment (although this does not always mean that fragment is destroyed). Before the end of the current user session, it is common to commit any changes that should persist here (because the user may no longer return).
(2) OnStop ()
The fragment is no longer visible. The hosted active host may have stopped, or modified the fragments that were made in the activity. This callback method is the same as the activity's onstop () purpose.
(3) Ondestroyview ()
When the view associated with the fragment is destroyed, this method is called to clean up the resources associated with the view.
(4) OnDestroy ()
This method is called when the fragment is no longer being used. At this point, the fragment is still associated with the activity, but no longer has functionality. This method should free the resources that the fragment is using, such as the Surfaceview used by the camera.
If the Setretaininstance (True) method is called, this method may be skipped. The workaround will be described in more detail later.
(5) Ondetach ()
This is the method that is called before the fragment is no longer associated with the activity. The view hierarchy for the fragment will not exist, at which point all resources used by the fragment should be freed.
(6) using the Setretaininstance () method
When rebuilding an activity, sometimes you may want to not destroy a specified fragment, in which case you can call the Setretaininstance () method to do this. If the argument passed to this method is true, the system will use the same fragment instance when the activity is restarted. If this happens, OnCreate () and OnDestroy () will no longer be called in the life cycle of the fragment, but other callback methods will still be called. This process is identified by a "green dashed line" in the above life cycle diagram.
3. Fragment State Management
In the life cycle of fragments, the state of fragment can be saved or restored through the bundle instance, because the bundle instance stores only "key/value" pairs in the form of strings, so it does not need to occupy too much memory. For example:
public override void Onsaveinstancestate (Bundle outstate)
{
Base. Onsaveinstancestate (outstate);
Outstate.putint ("Current_choice", currentcheckposition);
}
After you create an instance of fragment, you can read the status of the instance in the overridden onactivitycreated (). For example:
public override void Onactivitycreated (Bundle savedinstancestate)
{
Base. Onactivitycreated (savedinstancestate);
if (savedinstancestate! = null)
{
Currentcheckposition = Savedinstancestate.getint ("Current_choice", 0);
}
}
"Android" 11.4 fragment and its life cycle