Fragment表现Activity中用户界面的一个行为或者一部分,生命周期受宿主Activity生命周期的影响。
1.onAttach()
当fragment被绑定到activity时调用(Activity会被传入)
2.onCreate()
在创建fragment时系统会调用此方法。在实现代码中,你可以初始化想要在fragment中保持的那些必要组件,当fragment处于暂停或者停止状态之后可重新启用它们
3.onCreateView()
在第一次为fragment绘制用户界面时系统会调用此方法。为fragment绘制用户界面,这个函数必须要返回所绘出的fragment的根View。如果fragment没有用户界面可以返回空。
4.onActivityCreated()
当activity的onCreate()函数返回时被调用。
5.onStart()
显示之前调用
6.onReseme()
显示
7.onPause()
暂停,可以持久化数据,另一个activity处于前台且得到焦点,但是这个fragment所在的activity仍然可见(前台activity部分透明,或者没有覆盖全屏)。
8.onStop()
fragment不可见。要么宿主activity已经停止,要么fragment已经从activity上移除,但已被添加到后台栈中。一个停止的fragment仍然活着(所有状态和成员信息仍然由系统保留着)。但是,它对用户来讲已经不再可见,并且如果activity被杀掉,它也将被杀掉。
9.onDestoryView()
移除布局
10.onDestory()
销毁
11.onDetach()
接触与Activity关联
3个参数
public static class ExampleFragment extends Fragment {
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.example_fragment, container, false );
}
}
处理Fragment事务
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction .replace (R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction .commit ();
替换布局,保存前一个状态。
注:调用commit()并不立刻执行事务,相反,而是采取预约方式,一旦activity的界面线程(主线程)准备好便可运行起来。然而,如果有必要的话,你可以从界面线程调用executePendingTransations()立即执行由commit()提交的事务。但这样做,通常是没有必要的,除非其它线程的工作依赖与该项事务。
警告:只能在activity保存状态(当用户离开activity时)之前用commit()提交事务。如果你尝试在那时之后提交,会抛出一个异常。这是因为如果activity需要被恢复,提交后的状态会被丢失。对于这类丢失提交的情况,可使用commitAllowingStateLoss()
使用FragmentManager 可以做如下事情,包括:
1.使用findFragmentById()(用于在activity布局中提供有界面的fragment)或者findFragmentByTag()获取activity中存在的fragment(用于有界面或者没有界面的fragment)。
2.使用popBackStack()(模仿用户的BACK命令)从后台栈弹出fragment。
3.使用addOnBackStackChangedListener()注册一个监听后台栈变化的监听器。
与Activity交互,Activity实现接口,共享数据
public static class FragmentA extends ListFragment {
...
public interface OnArticleSelectedListener {
public void onArticleSelected (Uri articleUri);
}
...
}
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach (Activity activity) {
super .onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener" );
}
}
...
}
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onListItemClick (ListView l, View v, int position, long id) {
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
mListener.onArticleSelected(noteUri);
}
...
}
添加items到Action Bar(两种方法)
横竖屏转换
API