Fragment必须被“嵌入”Activity中使用,因此虽然Fragment也有生命周期,但其会受所在的Activity生命周期的控制。只有当Activity处于活动状态时,程序员才可通过方法独立地操作Fragment
- Fragment总是作为Activity界面的组成部分。Fragment通过getActivity()获取Activity;Activity通过findFragmentById()或findFragmentByTag()方法调取Fragment
- Activity运行过程中,可调用Fragment的add()、remove()、replace()方法动态地添加、删除活替换Fragment
- 一个Activity可以同时组合多个Fragment;一个Fragment也可被多个Activity复用
- Fragment可以响应自己的输入事件,并拥有自己的生命周期(但还是受其所在Activity控制)
由于Fragment是可复用组件,因此在手机上运行该应用,可以改为使用两个Activity:ActivityA包含FragmentA、ActivityB包含FragmentB
创建
实现Fragment与实现Activity非常相似
通常说来,创建Fragment需要实现如下三个方法:
- onCreate()
- onCreateView():该方法必须返回一个View,该View也就是该Fragment所显示的View
- onPause()
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (book != null) {
((TextView) rootView.findViewById(R.id.book_title))
.setText(book.title);
((TextView) rootView.findViewById(R.id.book_desc))
.setText(book.desc);
}
return rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (book != null) {
((TextView) rootView.findViewById(R.id.book_title))
.setText(book.title);
((TextView) rootView.findViewById(R.id.book_desc))
.setText(book.desc);
}
return rootView;
}
Fragment 与Activity通信
为了使用Fragment,需在Activity中添加。方式有:
- 布局文件中使用<fragment …/>
- Java代码中通过FragmentTransaction对象的add()
Activity的getFragmentManager()可返回FragmentManager,FragmentManager对象的beginTransaction()方法即可开启并返回FragmentTransaction对象
他们直接的数据传递可按如下方式进行:
- A向F:在A中创建Bundle数据包,并调用Fragment的setArgument(Bundle bundle)
- F向A:在F中定义一个内部回调接口,再让该Fragment所对应的A实现该接口
Fragment管理与Fragment事务
Activity管理Fragment主要依靠FragmentManager,FM有如下功能:
- findFragmentById或findFragmentByTag获取指定Fragment
- 调用popBackStack()将Fragment从后台栈中弹出
- 调用addOnBackStackChangeListener(),注册一个监听器,监听后台栈的变化
如果需要添加、删除、替换Fragment,则需要借助于FragmentTransaction
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();