您的位置:首页 > 其它

Fragment使用的基本流程

2016-03-17 15:22 225 查看

1.创建Fragment布局

根据自己的需求创建Fragment的布局

2.创建Fragment类,关联布局

For example, here's a subclass of
Fragment
that loads a layout from the
example_fragment.xml
file:

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>

其中container将传入其依赖的Activity的布局,savedInstanceState提供先前fragment的一个实例
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官方文档
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: