碎片的生命周期
与活动类似。碎片具有自己的生命周期。理解了碎片的生命周期后。我们能够在碎片被销毁时正确地保存事实上例,在碎片被重建时将其还原到前一个状态。
1、使用上一篇的项目Fragments。在Fragment1.java文件里加入例如以下代码:
package net.zenail.Fragments; import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d("Fragment 1", "onCreateView");
// 实例化布局文件
return inflater.inflate(R.layout.fragment1, container, false);
} @Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.d("Fragment 1", "onAttach");
} @Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("Fragment 1", "onCreate");
} @Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Log.d("Fragment 1", "onActivityCreated");
} @Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d("Fragment 1", "onStart");
} @Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("Fragment 1", "onResume");
} @Override
public void onPause() {
super.onPause();
Log.d("Fragment 1", "onPause");
}; public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d("Fragment 1", "onStop");
} @Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Log.d("Fragment 1", "onDestroyView");
} @Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("Fragment 1", "onDestroy");
} @Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.d("Fragment 1", "onDetach");
}
}2、按Ctrl+F11,将Android模拟器切换到横向模式;
3、在Eclipse中按下F11键。在模拟器上调试应用程序;
4、当应用程序载入到模拟器中后。LogCat窗体会显演示样例如以下内容:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemVuYWlsNTAxMTI5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
5、单击模拟器上的Homebutton,LogCat窗体中显演示样例如以下输出:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemVuYWlsNTAxMTI5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
6、在模拟器上长按Homebutton,再单击Fragments以启动应用程序,LogCat显演示样例如以下:
7、最后,单击模拟器中Backbutton,LogCat窗体显演示样例如以下输出:
8、由上面的实例可知。碎片经历的步骤例如以下:
碎片被创建时:onAttach()-->onCreate()-->onCreateView()-->onActivityCreated()。
碎片进入后台模式时:onPause()-->onStop()。
碎片变为可见时:onStart()-->onResume();
碎片被销毁时:onPause()-->onStop()-->onDestroyView()-->onDestroy()-->onDetach();
9、与活动一样,碎片能够使用Bundle对象在下面状态中还原碎片的实例:
onCreate()、onCreateView()、onActivityCreated()。