0、回顾
Fragment 代表 Activity 当中的一项操作或一部分用户界面。 一个 Activity 中的多个 Fragment 可以组合在一起,形成一个多部分拼接而成的用户界面组件,并可在多个 Activity 中复用。一个 Fragment 可被视为 Activity 中一个模块化的部分, 它拥有自己的生命周期,并接收自己的输入事件,在 Activity 运行过程中可以随时添加或移除它 (有点类似“子 Activity”,可在不同的 Activity 中重用)。
Fragment 必须嵌入某个 Activity 中,其生命周期直接受到宿主 Activity 生命周期的影响。 例如,当 Activity 被暂停(Paused)时,其内部所有的 Fragment 也都会暂停。 而当 Activity 被销毁时,它的 Fragment 也都会被销毁。 不过,在 Activity 运行期间(生命周期状态处于 恢复(Resumed) 状态时),每一个 Fragment 都可以被独立地操作,比如添加或移除。 在执行这些操作事务时,还可以将它们加入该 Activity 的回退栈(Back Stack)中 — Activity 回退栈的每个入口就是一条操作过的 Fragment 事务记录。 回退堆栈使得用户可以通过按下 回退(Back) 键来回退 Fragment 事务(后退一步)。
当把 Fragment 加入 Activity 布局(Layout) 后,它位于 Activity View 层次架构(Hierarchy)的某个 ViewGroup 里,且拥有自己的 View 布局定义。 通过在 Activity 的 Layout 文件中声明 <fragment> 元素,可以在 Layout 中添加一个 Fragment。 也可以用程序代码在已有的 ViewGroup 中添加一个 Fragment。 不过, Fragment 并不一定非要是 Activity 布局的一部分,它也可以没有自己的界面,而是用作 Activity 的非可视化工作组件。
1、概述
相信大家对Fragment的都不陌生,对于Fragment的使用,一方面Activity需要在布局中为Fragment安排位置,另一方面需要管理好Fragment的生命周期。Activity中有个FragmentManager,其内部维护fragment队列,以及fragment事务的回退栈。
一般情况下,我们在Activity里面会这么添加Fragment:
public class MainActivity extends FragmentActivity
{
private ContentFragment mContentFragment ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
mContentFragment = (ContentFragment) fm.findFragmentById(R.id.id_fragment_container);
if(mContentFragment == null )
{
mContentFragment = new ContentFragment();
fm.beginTransaction().add(R.id.id_fragment_container,mContentFragment).commit();
}
}
}










