Fragment life cycle Detailed

Source: Internet
Author: User
Tags hosting

Fragment life Cycle 1. Fragment Overview

Fragment introduced from Android v3.0 version

With the complexity of the interface layout, processing is also more complex, the introduction of fragment can be split into various parts of activity. Each fragment has its own layout and life cycle. facilitates the development.

UI management that uses fragment instead of activity to circumvent the restrictions on the activity rules of the Android system.

Fragment is a controller object that the activity can delegate to accomplish some tasks usually these tasks are managing the user interface. The managed user interface can be part of a full screen or a full screen. Fragment, which manages the user interface, is also known as UI fragment. It also has its own view that is generated from the layout file. The fragment view contains visual UI elements that users can interact with.

The activity hosting fragment, for the time being, can interpret hosting as activity to provide a place in its view hierarchy to place fragment views. The fragment itself does not have the ability to display views on the screen, so the fragment view can be displayed on the screen only if its view is placed in the activity's view hierarchy.

The advantage of using Fragment is that the business logic and UI can be packaged together, with no external connection, and other programs can use the component to maximize reuse.

2. Two ways to join fragment

First create the demo3fragment inherit the Fragment class and create an XML layout file for it

package com.ashzheng.studydemo.demo3;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.ashzheng.studydemo.R;public class Demo3Fragment extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_demo3, container, false);        return view;    }}

1. Through XML tags

Adding nodes to an activity's XML layout file

    <fragment            android:id="@+id/demo3_fg"            android:name="com.ashzheng.studydemo.demo3.Demo3Fragment"            android:layout_width="match_parent"            android:layout_height="0dp"            android:layout_weight="1"/>

2. Dynamic creation via code

    1. Add a container view in the activity's XML layout file

      <FrameLayout    android:id="@+id/demo3_layout"    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="1"/>
    2. Dynamically add fragment in activity

      package com.ashzheng.studydemo.demo3;import android.app.Activity;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.os.Bundle;import com.ashzheng.studydemo.R;public class Demo3Activity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_demo3);        FragmentManager fragmentManager = getFragmentManager();        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        fragmentTransaction.add(R.id.demo3_layout, new Demo3Fragment());        fragmentTransaction.commit();    }}
3. Fragment Life cycle

The fragment life cycle is similar to the activity's life cycle. The correspondence of the life cycle method is very important, because fragment represents activity at work, and its state should also reflect the state of the activity. Thus, the fragment needs a corresponding life cycle approach to work with the activity.

The effect of these methods is given in the comments in the code

Fragment 1.                    Interface Open OnCreate () method Execution!                 Oncreateview () Method Execution!       Onactivitycreated () Method Execution!    OnStart () Method Execution! Onresume () Method Execution!    2. Press the main screen key/Lock screen OnPause () method to execute! OnStop () Method Execution!    3. Reopen the OnStart () method to execute! Onresume () Method Execution!    4. Press the Back Key OnPause () method to execute!    OnStop () Method Execution!    Ondestroyview () Method Execution!    OnDestroy () Method Execution! Ondetach () Method Execution! Activity 1.    Open the App OnCreate () method to execute!    OnStart () Method Execution!    Onresume () Method Execution!    2. Press the main screen key/Lock screen OnPause () method to execute!    OnStop () Method Execution!    3. Reopen the application Onrestart () method to execute!    OnStart () Method Execution!    Onresume () Method Execution!     4. Press the Back Key OnPause () method to execute!      OnStop () Method Execution! OnDestroy () Method Execution! Add fragment to the activity, corresponding to the life cycle of 1. Open the Fragment OnCreate () method to execute! Fragment Oncreateview () method Execution! Activity onCreate () method Execution! Fragment onactivitycreated () method Execution! Activity OnStart () method Execution! Fragment OnStart () method Execution! Activity Onresume () method Execution! Fragment Onresume () method Execution! 2. Press the main screen key/lock screen fragment OnPause () method to execute! Activity OnpausE () Method execution! Fragment onStop () method Execution! Activity onStop () method Execution! 3. Open the Activity Onrestart () method again to execute! Activity OnStart () method Execution! Fragment OnStart () method Execution! Activity Onresume () method Execution! Fragment Onresume () method Execution! 4. Press the back key fragment OnPause () method to execute! Activity onPause () method Execution! Fragment onStop () method Execution! Activity onStop () method Execution! Fragment Ondestroyview () method Execution! Fragment OnDestroy () method Execution! Fragment Ondetach () method Execution! Activity OnDestroy () method Execution!

The activity's Fragmentmanager is responsible for invoking the fragment lifecycle method in the queue, adding fragment for Fragmentmanager management, Onattach (Activity), The Oncreat (Bundle) and Oncreatview () methods are called.

The onactivitycreated () method is also called after the OnCreate () method of the managed activity is executed. Because fragment is being added to the Activity.oncreat () method, the method is called when fragment is added.

What happens when you add fragment when activity is stopped, paused, or running? In this case, Fragmentmanager immediately drives fragment to keep pace with the activity until it is in sync with the latest state of activity. For example, when adding fragment to an activity in the running state, the following fragment life-cycle methods are called sequentially: Onattch (), Oncreat (), Oncreatview (), onactivitycreated (), OnStart (), and the Onresume () method.

As long as the state of the fragment is kept in sync with the state of the activity, the fragmentmanager of the managed activity will continue to invoke other life cycle methods to continue to maintain fragment consistent with the activity, and almost at the same time, It receives a corresponding call from the operating system. However, it is not guaranteed whether the fragment method is invoked before or after the activity method.

A key difference between the fragment life cycle and the activity life cycle is that the fragment lifecycle approach is called by managed activity rather than by the operating system. The operating system does not know the fragment that activity uses to manage views. The use of fragment is the activity of their own internal affairs. It can be found that thelife cycle method in activity is protected, while fragment ispublic, because fragment is managed by activity, and the activity needs to invoke these methods.

Data saving in 4.Fragment

As in activity, fragment also provides the Onsaveinstancestate () method, using the same basic and activity, unlike in fragment, although Fragment.oncreate () The fragment method configures the instance, but creating and configuring the Fragment view is done through the Fragment.oncreateview () method. Therefore, the data used to reconstruct the view in the saved state can be obtained in the Fragment.oncreateview () method.

Specific code:

Demo3fragment

Package Com.ashzheng.studydemo.demo3;import Android.app.fragment;import Android.content.context;import Android.os.bundle;import Android.util.log;import Android.view.layoutinflater;import Android.view.View;import Android.view.viewgroup;import Com.ashzheng.studydemo.r;public class Demo3fragment extends Fragment {@Override publi        c void Onattach (context context) {//When fragment is first associated with Activity, it is not called super.onattach (context); LOG.D ("Demoinfo", "Fragment Onattach () method Execution!    "); } @Override public void OnCreate (Bundle savedinstancestate) {//Will call this method immediately after execution of the Onattach, which is typically used to read the saved state value, get or initialize        Some data,//But the method does not execute, the window is not displayed, so if the obtained data requires access to the network, the best new thread.        Super.oncreate (savedinstancestate); LOG.D ("Demoinfo", "Fragment onCreate () method Execution!    ");        } @Override Public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { Create the view displayed in the Fragment, where inflater is used to load the layout file, container represents the parent tag of the <fragment> tag corresponding to theViewGroup object,//Savedinstancestate can get Fragment saved state log.d ("Demoinfo", "Fragment oncreateview () method Execution!"        ");        if (null! = savedinstancestate) {log.d ("Demoinfo", "Saved data:" + savedinstancestate.getstring ("MyInfo")); }else {log.d ("Demoinfo", "No Data Saved!")        ");        } View view = Inflater.inflate (R.layout.fragment_demo3, container, false);    return view; @Override public void onactivitycreated (Bundle savedinstancestate) {//is called this method immediately after the Activity.oncreate () method call.        Indicates that the window has been initialized and the control can be called super.onactivitycreated (savedinstancestate); LOG.D ("Demoinfo", "Fragment onactivitycreated () method Execution!    ");        } @Override public void OnStart () {//Start execution of the control-related logic code, such as keystrokes click Super.onstart (); LOG.D ("Demoinfo", "Fragment onStart () method Execution!    ");        } @Override public void Onresume () {//This is the method Fragment from creation to the last callback shown Super.onresume (); LOG.D ("Demoinfo", "Fragment onresume () method Execution!    "); } @OvErride public void OnPause () {//When an interface jump occurs, a temporary pause, pause time is 500ms,0.5s directly into the following OnStop method Super.onpause (); LOG.D ("Demoinfo", "Fragment onPause () method Execution!    ");        } @Override public void OnStop () {//When the method returns, Fragment disappears from the screen super.onstop (); LOG.D ("Demoinfo", "Fragment onStop () method Execution!    ");        } @Override public void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate); LOG.D ("Demoinfo", "Fragment onsaveinstancestate () method Execution!        ");    Outstate.putstring ("MyInfo", "haha");        } @Override public void Ondestroyview () {//When fragment state is saved, or ejected from the fallback stack, the method is called Super.ondestroyview (); LOG.D ("Demoinfo", "Fragment ondestroyview () method Execution!    ");        } @Override public void OnDestroy () {//When Fragment is no longer being used, such as pressing the return key, this method is called Super.ondestroy (); LOG.D ("Demoinfo", "Fragment OnDestroy () method Execution!    "); } @Override public void Ondetach () {The last method of the//fragment life cycle, after execution will no longer be associated with ActivityWill release all fragment objects and resources super.ondetach (); LOG.D ("Demoinfo", "Fragment Ondetach () method Execution!    "); }}

Demo3activity

Package Com.ashzheng.studydemo.demo3;import Android.app.activity;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.util.log;import Com.ashzheng.studydemo.R;        public class Demo3activity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_DEMO3); LOG.D ("Demoinfo", "Activity onCreate () method Execution!") ");//Fragmentmanager Fragmentmanager = Getfragmentmanager ();//Fragmenttransaction fragmenttransaction = fr Agmentmanager.begintransaction ();//Fragmenttransaction.add (R.id.demo3_layout, New Demo3fragment ());//FRAGM    Enttransaction.commit ();        } @Override protected void OnDestroy () {Super.ondestroy (); LOG.D ("Demoinfo", "Activity OnDestroy () method Execution!")    ");        } @Override protected void OnPause () {super.onpause (); LOG.D ("Demoinfo", "Activity onPause () method Execution!")");        } @Override protected void Onrestart () {Super.onrestart (); LOG.D ("Demoinfo", "Activity onrestart () method Execution!")    ");        } @Override protected void OnStart () {Super.onstart (); LOG.D ("Demoinfo", "Activity onStart () method Execution!")    ");        } @Override protected void OnStop () {super.onstop (); LOG.D ("Demoinfo", "Activity onStop () method Execution!")    ");        } @Override protected void Onresume () {super.onresume (); LOG.D ("Demoinfo", "Activity onresume () method Execution!")    "); }}

Activity_demo3.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.ashzheng.studydemo.demo3.Demo3Activity">    <fragment        android:id="@+id/demo3_fg"        android:name="com.ashzheng.studydemo.demo3.Demo3Fragment"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"/>    <FrameLayout        android:id="@+id/demo3_layout"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"/> </LinearLayout>

Total Project Address: Https://github.com/zhenggy/AndroidStudyDemo

Fragment life cycle Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.