An example is given to explain the control of fragment life cycle in Android application development

1、 On the life cycle of fragment

Because fragment must be embedded in activity, its life cycle is closely related to its activity.

If the activity is suspended, all fragments are suspended; If the activity is in the stopped state, all fragments in the activity cannot be started; If an activity is destroyed, all fragments in it will be destroyed.

However, when the activity is active, you can independently control the state of fragments, such as adding or removing fragments.

When performing fragment transaction in this way, you can put the fragment into the back stack of the activity, so that the user can return.

When using fragment, you need to inherit fragment or its subclasses (dialogfragment, listfragment, preferencefragment, webviewfragment), so the code of fragment looks similar to that of activity.

Whenever a fragment is created, first add the following three callback methods:

Oncreate(): the system calls this method when creating a fragment. Here, the relevant components should be initialized, and some things still need to be retained even when it is suspended or stopped. Oncreateview(): this method is called when drawing the UI of the fragment for the first time. This method will return a view. If the fragment does not provide UI, it can also return null. Note that if you inherit from listfragment, the default implementation of oncreateview () will return a listview, so you don't need to implement it yourself. Onpause (): this method is called first when the user leaves the fragment, and some changes need to be submitted, because the user is likely not to return. There are two ways to load fragments into an activity:

Method 1: add fragments to the activity's layout file method 2: dynamically add fragments to the activity's code. Although the first method is simple, it is not flexible enough. Adding a fragment to the activity's layout file is equivalent to binding the fragment and its view to the activity's view, and the fragment view cannot be switched during the activity's life cycle.

The second method is more complex, but it is also the only way to control fragments at run time (load, remove, replace).

2、 Life cycle control instance

Result: oncreate procedure

OnStart process

Onresume procedure

Onpause process

Onstop process

OnStart process

Onresume procedure

Onpause process

Onstop process

Ondestroy process

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
分享
二维码
< <上一篇
下一篇>>