1.创建Fragment布局
根据自己的需求创建Fragment的布局
2.创建Fragment类,关联布局
For example, here's a subclass of
Fragment
that loads a layout from theexample_fragment.xml
file:其中container将传入其依赖的Activity的布局,savedInstanceState提供先前fragment的一个实例public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); } }<span class="pun"></span>
infate()方法有三个参数,第一个为fragment的布局,第二个为父类的布局,第三个布尔型的参数为制定fragment是否要插入到父类的activity布局中,这里为false因为已经在父类的activity中插入了这个fragment
3.将Fragment加入到Activity中
有两种方法,一种是在activity的布局中直接加入fragment,另一种是使用FragmentManager
使用FragmentManager分为4步:
1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。
2.开启一个事务,通过调用beginTransaction方法开启。
3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。
4.提交事务,调用commit方法提交。
详情见郭霖的博客: Android Fragment完全解析,关于碎片你所需知道的一切和Android官方文档