Detailed explanation of fragment definition, creation and use of Android development tutorial [including activity communication, transaction execution, etc.]

This paper describes the definition, creation and use of fragment in Android development tutorial. Share with you for your reference, as follows:

summary

Fragment is a part or a behavior in the interface of an activity. You can combine multiple fragments into one activity to create a multifaceted interface, and you can reuse one fragment in multiple activities. You can think of fragment as a modular activity. It has its own life cycle, receives its own events, and can be added or deleted when the activity runs.

A fragment cannot exist independently. It must be embedded into an activity, and its life cycle is directly affected by the activity in which it is located. For example, when an activity is suspended, all its fragments are suspended. When an activity is destroyed, all its fragments are destroyed. However, when the activity runs (after onresume () and before onpause ()), you can manipulate each fragment individually, such as adding or deleting them. When you execute the above transaction for fragment, you can add the transaction to a v-activity management. Each item in the stack is a transaction of a fragment. With this stack, fragment transactions can be executed in reverse, so that the "back" key (backward navigation) can be supported at the fragment level.

When adding a fragment to an activity, it must be placed in the ViewGroup control, and the fragment's own interface needs to be defined. You can declare fragment in the layoutxml file. The elements are: < fragment >; You can also create a fragment in your code and add it to the ViewGroup control. However, fragment does not have to be placed in the interface of activity. It can be hidden in the background to work for activity.

Next, let's talk about how to use fragments, including how to use fragments to share events with other fragments, how to display them in the action bar of the activity, and so on.

Android has introduced fragment since 3.0, mainly to support more dynamic and flexible interface design, such as applications on tablets. Tablets have more screen space than mobile phones to combine and interact with interface components. Fragment allows you to make such a design without dealing with complex changes in the view tree. By dividing the layout of an activity into fragments, you can change its appearance when the activity is running, and you can save these changes in the back stack of the activity.

For example, when writing a program to read news, you can use one fragment to display the title list and the other fragment to display the content of the selected title. Both fragments are displayed side by side on the same activity. Then both fragments have their own life cycles and respond to events of interest to them. Therefore, it is no longer necessary to use one activity to display the title list and another activity to display the news content as on the mobile phone; Now you can display both on one activity at the same time.

Fragments must be written as reusable modules. Because a fragment has its own layout, its own event response, and its own life cycle and behavior, you can include different instances of the same fragment in multiple activities. This is especially important to make your interface give users a perfect experience under different screen sizes. For example, you can start an activity with many fragments when the program runs on a large screen, and an activity with a small number of fragments when the program runs on a small screen.

For example, when you detect that the program is running on the large screen, start activitya, and you put the two fragments of title list and news content in activitya; When it is detected that the program is running on a small screen, activitya is still started, but there is only a title list fragment in A. when a title is selected, activitya starts activityb, which contains news content fragment.

Life cycle of fragments

Each fragment has its own set of lifecycle callback methods and processes its own user input events. Refer to the following figure for the corresponding life cycle:

Creating a fragment

To create a fragment,you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity,such as onCreate(),onStart(),onPause(),and onStop(). In fact,if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.

To create a fragment, you must create a subclass of the fragment (or a subclass inherited from it). The code of the fragment class looks like activity. Like activity, it has callback functions, such as oncreate(), onstart(), onpause(), and onstop(). In fact, if you are converting an existing Android application to fragment, you can simply migrate the code from the callback function of activity to their fragment callback function.

Normally, you should implement at least the following lifecycle methods: oncreate() the system calls this when creating the fragment. Within your implementation, You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. In the implementation code, you can initialize the necessary components that you want to keep in the fragment (the components here refer to things other than the view, such as the key data that needs to be displayed on the interface). When the fragment is in the suspended or stopped state, you can re enable them.

onCreateView() The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, You must return a view from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI. To draw the user interface for the fragment, this function must return the root view of the drawn fragment. If the fragment has no user interface, it can return null.

onPause() The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back) The system callback uses this function as the first sign that the user leaves the fragment (although this does not always mean that the fragment is destroyed). Before the end of the current user session, any changes that should be persisted are usually submitted here (because the user may no longer return).

Most applications should implement at least these three methods for every fragment,but there are several other callback methods you should also use to handle varIoUs stages of the fragment lifecycle. All the lifecycle callback methods are discussed more later, In the section about handling the fragment lifecycle. Most applications should implement at least these three methods for each fragment, but there are many other callback functions used to manipulate each stage of the fragment lifecycle. Callback functions in all lifecycles are discussed later in the manipulating fragment lifecycles section.

There are also a few subclasses that you might want to extend, instead of the base fragment class:

Dialogfragment displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a missed fragment. Using this class to create a dialog box is another good choice other than using the activity class dialog tool method, because you can incorporate the fragment dialog box into the fragments background stack managed by the activity, allowing users to return to a discarded fragment.

Listfragment displays a list of items that are managed by an adapter (such as a simplecursoradapter), simple to listactivity. It provides several methods for managing a list view, such as the onlistitemclick() callback to handle click events. It also provides many functions to manage the list view, such as the onlistitemclick() callback function to handle the click event.

Preferencefragment displays a hierarchy of preference objects as a list, similar to preferenceactivity. This is useful when creating a "Settings" activity for your application. This is useful when creating a "Settings" activity for an application.

Implement the interface of fragment

To add a user interface to a fragment:

Fragment, as a part of the user interface of an activity, embeds its own layout into the layout of the activity. To provide layout for a fragment, you must implement the oncreateview() callback method, and then return a view object in this method, which is the root of the layout of the fragment.

Note: if your fragment is derived from listfragment, you don't need to implement oncreateview () method, because the default implementation has returned the listview control object for you.

To return the layout object from the oncreateview () method, you can generate the layout object from the layoutxml. To help you do this, oncreateview () provides a layoutinflator object.

Example: the following code shows how a subclass of fragment can be generated from the layoutxml file example_ Generate objects in fragment.xml.

The container in the oncreateview () parameter is the ViewGroup object that holds the layout of the fragment. The savedinstancestate parameter is a bundle, similar to the bundle in oncreate() of an activity, used for state recovery. However, the fragment oncreate() also has a bundle parameter, so the data stored in the bundle here is different from that stored in oncreate(). For details, please refer to the section "manipulating the lifecycle of fragments".

The inflate () method has three parameters:

Resource ID of 1 layout.

2. The ViewGroup that stores the layout of the fragment.

3 Boolean data indicates whether the layout is attached to the container during the creation of the layout of the fragment (in this example, the value is false because the system has inserted the layout into the container. If it is true, it will lead to the creation of redundant viewgroups in the final layout (I can't understand this sentence, but my translation should be correct)).

Now that you have seen how to create a layout for the fragment, the following describes how to add it to the activity.

Add fragment to activity

Generally, a fragment combines its layout into an activity as part of the deployment of an activity. There are two ways to add a fragment to an activity:

Method 1: declare fragment in the activity's layoutxml file

In the following code, an activity contains two fragments:

Declare a fragment in < fragment >. When the system creates the layout in the example, it instantiate every fragment and then calls the onCreateView () method to get the layout of each fragment. The system inserts the view object returned by the fragment into the position of the < fragment > element to directly replace the < fragment > element.

Note: each fragment needs to provide an ID. the system uses it to restore fragments when the activity is recreated. You can also use it to operate the fragment for other things, such as deleting it. There are three ways to provide an ID to a fragment:

1 assign a specific identifier to the Android: ID attribute. 2 assign a tag name to the Android: tag attribute. 3 if you do not use any of the above methods, the system will use the ID of the fragment container.

Method 2: add a fragment to a ViewGroup in the code

This method can add the fragment to the layout of the activity at run time. You only need to specify a ViewGroup to contain fragments.

In order to complete fragment transactions (such as adding, deleting, replacing, etc.), you must use the fragmenttransaction method. You can get the fragmenttransaction from the activity, as follows:

Then you can add a fragment with the add () method, which has parameters to specify the ViewGroup that holds the fragment. As follows:

The first parameter of add() is the container ViewGroup, and the second is the fragment to be added. Once you make changes to the fragment through the fragmenttransaction, you must call the method commit () to commit the changes.

Tag can also be used as a flag not only in fragments without interfaces, but also in fragments with interfaces. In this way, findfragmenttag() should be called when fragment objects need to be obtained.

Add a fragment without an interface

The above shows how to add fragments to provide interfaces. However, you can also use fragments to provide background behavior for activities without displaying the fragment interface.

To add a fragment with no interface, you need to invoke method add (Fragment, String) in activity (which supports the use of a unique string as fragment tag instead of viewID). The fragment added in this way has no interface, so you don't need to call the oncreateview () method when implementing it.

Using tag string to identify a fragment is not only used for fragments without interface. You can also use it for fragments with interface. However, if a fragment has no interface, tag string will become its only choice. To obtain the fragment identified by tag, use the method findfragmentbytab().

Manage fragment

To manage fragment, you need to use FragmentManager. To get it, you need to invoke method getFragmentManager () in activity.

You can use the fragmentmanager to do the above:

1 use the method findfragmentbyid() or findfragmentbytag() to obtain the existing fragments in the activity. 2. Use the method popbackstack() to pop up fragments from the activity's back stack (this can simulate the action caused by the back key). 3 register a listener with the method addonbackstackchangedlisterner () to monitor changes in the backoff stack.

You can also use the fragment manager to open a fragment transaction to execute fragment transactions, such as adding or deleting fragments.

Execute fragment transactions

One of the great benefits of using fragments in an activity is the ability to add, delete, replace, and perform other actions based on user input. A set of fragment changes you submit is called a transaction. The transaction is executed through the fragmenttransaction. You can also save each transaction in the activity's back stack, which allows users to navigate between fragment changes (just like navigating between activities).

You can obtain the instance of fragmenttransaction through fragmentmanager, as follows:

A transaction is a set of actions executed at the same time (much like a transaction in a database). You can use add (), remove (), replace () and other methods to form a transaction, and finally use the commit () method to commit the transaction.

Before calling commit (), you can use addtobackstack () to add the transaction to a backward stack that belongs to the activity. With it, you can return to the state before the fragments execute the transaction when the user presses the back key.

The following example demonstrates how to replace one fragment with another, and save the state of the replaced fragment in the backward stack.

Explanation: newfragment replaces the control idr.id.fragment_ Any fragments contained in the ViewGroup pointed to by the container. Then the addToBackStack () is called, and the replaced fragment is placed in the back stack, so when the user presses the return key, the transaction will backtrack and the original fragment will be back.

If you add multiple actions to the transaction, such as calling add (), remove (), and then calling the addToBackStack () method, all the methods that are called before commit () are treated as a transaction. When the user presses the return key, all actions are executed in the reverse direction (transaction backtracking).

The execution sequence of actions in a transaction can be arbitrary, but pay attention to the following two points:

1. you must call commit () last.

2. If you add multiple fragments, their display order is the same as the addition order from one to (the displayed after overrides the one in front).

If you delete fragments in the executed transaction without calling addtobackstack (), those deleted fragments will be destroyed when the transaction is committed. On the contrary, those fragments will not be destroyed, but will be stopped. When the user returns, they are restored.

Secret technique: for fragment transactions, you can apply animation. It is OK to call setTransition () before commit (). I won't tell him.

However, after calling commit (), the transaction will not be executed immediately. It will wait in the UI thread of the activity (actually the main thread) until the thread can execute (nonsense). If necessary, you can call the executePendingTransactions () method in the UI thread to execute the transaction immediately. However, you generally do not need to do so unless there are other threads waiting for the execution of the transaction.

Warning: you can only commit transactions when the activity is in a saveable state, such as in running, onpause () method and onstop () method, otherwise an exception will be thrown. This is because the state of the fragment will be lost. If you want to commit a transaction in case of possible loss of state, use commitallowingstateloss().

Fragment communicates with activity

Although the implementation of fragment is independent of activities and can be used for multiple activities, each activity contains different instances of the same fragment.

Fragment can call getactivity () method to easily get the object of its activity, and then find the controls in the activity (findviewbyid()). For example:

Similarly, an activity can find the frames it contains through the fragmentmanager method. For example:

Activity responds to the event of the fragment

Sometimes, you may need fragments to share events with activities. A good idea is to define a callback interface in the fragment and then implement it in the activity.

For example, the news program has an activity that contains two fragments. Fragment a displays the news title and fragment B displays the content corresponding to the title. Fragment a must tell activity when the user selects a title, and then activity tells fragment B, and fragment B will display the corresponding content (why is it so troublesome? Just tell fragmenta to fragmentb directly? It's OK, but your fragment reduces the reusability. Now I just need to tell my event to the host and let the host decide how to deal with it. Is it better to reuse it?) for example, onarticleselectedlistener interface is defined in fragmenta:

Then, the activity implements the interface onarticleselectedlistener and notifies fragmentb in the method onarticleselected(). When a fragment is added to an activity, the fragment method onattach () will be called. This method is suitable for checking whether the activity implements the onarticleselectedlistener interface. The checking method is to type convert the instance of the incoming activity, as shown below:

If the activity does not implement that interface, the fragment throws a ClassCastException exception. If successful, the mlistener member variable holds an instance of onarticleselectedlistener. Fragment a can then call the method of mlistener to share events with the activity. For example, if fragmentA is a ListFragment, every time you select a list, you call the onListItemClick () method of fragmentA, calling onArticleSelected () in this method to share events with activity, as follows:

The parameter ID passed in by onlistitemclick() is the ID of the selected row of the list. Another fragment uses this ID to get the content of the title from the ContentProvider of the program.

Fragment application example

Add entry to action bar

Your fragments can add items to the activity menu (what appears when you press the manu key) and to the action bar (the area at the top of the interface). This needs to be done by implementing the method oncreateoptionmanu().

Any item you add to the menu from the fragment will appear after the existing menu item. After fragment, you can respond to the event that your menu item is selected through the method onoptionsitemselected().

You can also register a view in fragemnt to provide a shortcut menu (context menu). When the user wants to open the shortcut menu, the oncreatecontextmenu () method of the fragment will be called. When the user selects one of the items, the oncontextitemselected () method of fragemnt is called.

Note: although your fragment can receive the selected events of the added menu items respectively, the activity is the first guy to receive these events. The fragment can receive this event only when the activity ignores an event, which is the same for menus and shortcut menus.

In the following example, all the contents mentioned above are experimented. This example has an activity that contains two fragments. One shows the playing tracks of Shakespeare's plays, and the other shows the summary of the selected tracks. This example also demonstrates how to configure fragments according to the screen size.

MainActivity:

Layout.xml:

When the activity loads this layout, the system initializes titlesfragment (used to display the title list). To the right of titlesfragment is a FrameLayout, which is used to store the fragments displaying the summary, but now it is still empty. The summary fragment will be placed in the FrameLayout only after the user selects a title.

However, not all screens have enough width to accommodate Title lists and summaries. Therefore, the above layout is only used for horizontal screen. Now it is stored in RET / layout land / fragment_ layout.xml。

In addition, when used for vertical screen, the system uses the following layout, which is stored in RET / layout / fragment_ layout.xml:

This layout contains only titlesfragment. This means that when using the vertical screen, only the title list is displayed. When the user selects an item, the program will start a new activity to display the summary instead of loading the second fragment.

Next, you will see the implementation of the fragment class. The first is titlesfragment, which is derived from listfragment. Most of the functions of lists are provided by listfragment.

When a user selects a title, the code needs to do two actions: one is to create and display the summary fragment in the same activity, and the other is to start a new activity.

The second fragment, detailsfragment, displays the summary of the selected title:

If the current layout does not have r.id.detailsview (which is used as a container for detailsfragment), the program starts detailsactivity to display the summary.

The following is the detailsactivity, which simply embeds detailsfragment to display the summary.

Note that this activity will end itself when it detects that it is a vertical screen, so the main activity will take over it and display titlesfragment and detailsffragment. This can be displayed in the titlefragment when the user is in the vertical screen, but the user rotates the screen to make the display horizontal.

More readers interested in Android related content can view the topics on this site: summary of Android basic component usage, introduction and advanced tutorial of Android development, summary of Android layout skills, summary of Android view skills, summary of activity operation skills of Android programming, summary of Android resource operation skills, and Android control usage summary

I hope this article will help you in Android programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>