- 自定义lifecycleoffragment布局文件
- 在main_activity布局中引用自定义的fragment布局
- 到logcat中查看程勋运行的结果
- 代码如下:
自定义的fragment布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是展示LifeCycleOfFragment,请到logcat中查看"
android:textColor="#000000"
android:textSize="25sp"
/>
</LinearLayout>
Fragment的java类
package com.cm.lifecycleoffragment;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Administrator on 2016/1/2.
*/
public class LifeCycleOfFragment extends Fragment{
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d("lifecycleoffragment","onAttach()");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("lifecycleoffragment","onCreate()");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("lifecycleoffragment","onCreateView()");
return inflater.inflate(R.layout.lifecycleof_fragment,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("lifecycleoffragment", "onActivityCreated()");
}
@Override
public void onStart() {
super.onStart();
Log.d("lifecycleoffragment", "onStart()");
}
@Override
public void onResume() {
super.onResume();
Log.d("lifecycleoffragment", "onResume()");
}
@Override
public void onPause() {
super.onPause();
Log.d("lifecycleoffragment", "onPause()");
}
@Override
public void onStop() {
super.onStop();
Log.d("lifecycleoffragment", "onStop()");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d("lifecycleoffragment", "onDestroyView()");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("lifecycleoffragment", "onDestroy()");
}
@Override
public void onDetach() {
super.onDetach();
Log.d("lifecycleoffragment", "onDetach()");
}
}
在main_activity的布局文件中引用fragment
<RelativeLayout 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"
tools:context=".MainActivity">
<fragment
android:name="com.cm.lifecycleoffragment.LifeCycleOfFragment"
android:id="@+id/lifecycleof_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Logcat打印的程序运行过程:
按home键返回的运行过程:
再次进入程序的运行过程:
按ctrl+f11程序的运行过程:
按back键的运行过程:
以上过程充分展示fragment的生命周期。