Fragment生命周期

Fragment是Android3.0时引入的用于解决大屏设备视图布局的一个组件。它应理解为片段或者直接就是一个块。Fragment是不能单独存在的,它必须依赖与Activity。

如何创建一个Fragment:需继承Fragment这个类,4.0之前可以使用V4兼容包的Fragment,4.0开始有单独的Fragment。

如果使用Fragment:通过以下代码加载

 1 package com.baixd.app.framework.fragment;
 2 
 3 import android.app.Fragment;
 4 import android.app.FragmentManager;
 5 import android.app.FragmentTransaction;
 6 import android.support.v7.app.ActionBarActivity;
 7 import android.os.Bundle;
 8 import android.view.Menu;
 9 import android.view.MenuItem;
10 import android.widget.Toast;
11 
12 import com.baixd.app.framework.R;
13 
14 public class CommunicationActivity extends ActionBarActivity{
15 
16     @Override
17     protected void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.activity_communication);
20 
21         FragmentManager fragmentMgr = getFragmentManager();
22         FragmentTransaction transaction = fragmentMgr.beginTransaction();
23 
24         Fragment fragment = new CommunicationFragment();
25 
26         transaction.replace(R.id.ll_communication, fragment);
27         transaction.commit();
28     }
29 
30 }

CommunicationActivity对应的布局文件activity_communication.xml

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context="com.baixd.app.framework.fragment.CommunicationActivity">
10 
11     <TextView
12         android:id="@+id/tv_communication"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="@string/hello_world" />
16 
17     <LinearLayout
18         android:id="@+id/ll_communication"
19         android:layout_width="match_parent"
20         android:layout_height="wrap_content"
21         android:layout_below="@id/tv_communication"
22         android:orientation="horizontal">
23 
24     </LinearLayout>
25 
26 </RelativeLayout>

Fragment与Activity一样,也有自己的生命周期,但它的生命周期在宿主Activity内。通过代码的简单Log试验,总结他的生命周期过程如下:

1 /**
2      * 1)加载Fragment onAttach --> onCrate --> onCreateView --> onActivityCreated --> onStart --> onResume
3      * 2)按返回键 onPause --> onStop --> onDestroyView --> onDestroy --> onDetach
4      * 3)在加载了Fragment的页面内 锁屏 onPause --> onStop
5      * 4)在加载了Fragment的页面内 解锁 onStart --> onResume
6      * 5)在加载了Fragment的页面内 HOME onPause --> onStop
7      * 6)销毁activity onPause --> onStop --> onDestroyView --> onDestroy --> onDetach
8      */
原文地址:https://www.cnblogs.com/blacksonny/p/4279338.html