Android在3.0中引入了fragments的概念,主要目的是用在大屏幕设备上--例如平板电脑上,支持更加动态和灵活的UI设计。平板电脑的屏幕要比手机的大得多,有更多的空间来放更多的UI组件,并且这些组件之间会产生更多的交互。Fragment允许这样的一种设计,而不需要你亲自来管理 viewhierarchy的复杂变化。 通过将activity的布局分散到fragment中, 你可以在运行时修改activity的外观,并在由activity管理的back stack中保存那些变化.()
例如, 一个新闻应用可以在屏幕左侧使用一个fragment来展示一个文章的列表,然后在屏幕右侧使用另一个fragment来展示一篇文章--2个fragment并排显示在相同的一个activity中,并且每一个fragment拥有它自己的一套生命周期回调方法,并且处理它们自己的用户输入事件。 因此, 取代使用一个activity来选择一篇文章而另一个activity来阅读文章的方式,用户可以在同一个activity中选择一篇文章并且阅读, 如图所示:
fragment在你的应用中应当是一个模块化和可重用的组件.即,因为fragment定义了它自己的布局, 以及通过使用它自己的生命周期回调方法定义了它自己的行为,你可以将fragment包含到多个activity中. 这点特别重要, 因为这允许你将你的用户体验适配到不同的屏幕尺寸.举个例子,你可能会仅当在屏幕尺寸足够大时,在一个activity中包含多个fragment,并且,当不属于这种情况时,会启动另一个单独的,使用不同fragment的activity.
继续之前那个新闻的例子 -- 当运行在一个特别大的屏幕时(例如平板电脑),应用可以在Activity A中嵌入2个fragment。然而,在一个正常尺寸的屏幕(例如手机)上,没有足够的空间同时供2个fragment用, 因此, Activity A会仅包含文章列表的fragment, 而当用户选择一篇文章时, 它会启动ActivityB,它包含阅读文章的fragment.因此, 应用可以同时支持上图中的2种设计模式。
通常, 应当至少实现如下的生命周期方法:
其生命周期图如下:
fragment通常用来作为一个activity的用户界面的一部分,并将它的layout提供给activity.为了给一个fragment提供一 个layout,你必须实现 onCreateView()回调方法, 当到了fragment绘制它自己的layout的时候,Android系统调用它.你的此方法的实现代码必须返回一个你的fragment的 layout的根view.
注意: 如果你的fragment是ListFragment的子类,它的默认实现是返回从onCreateView()返回一个ListView,所以一般情况下不必实现它.
从onCreateView()返回的View, 也可以从一个layout的xml资源文件中读取并生成. 为了帮助你这么做, onCreateView() 提供了一个LayoutInflater 对象.
举个例子, 这里有一个Fragment的子类, 从文件 example_fragment.xml 加载了一个layout:
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);
}
}
传入onCreateView()的container参数是你的fragmentlayout将被插入的父ViewGroup(来自activity的layout) savedInstanceState 参数是一个Bundle, 如果fragment是被恢复的,它提供关于fragment的之前的实例的数据,
inflate() 方法有3个参数:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
<fragment> 中的 android:name属性指定了在layout中实例化的Fragment类.有3种方法来为一个fragment提供一个标识:
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
然后你可以使用 add() 方法添加一个fragment, 指定要添加的fragment和要插入的view.
ExampleFragment fragment = newExampleFragment();
fragmentTransaction.add(R.id.fragment_container,fragment);
fragmentTransaction.commit();
add()的第一个参数是fragment要放入的ViewGroup, 由resource ID指定,第二个参数是需要添加的fragment.一旦用FragmentTransaction做了改变,为了使改变生效,必须调用commit().
要在activity中管理fragment,需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例.
可以通过FragmentManager做一些事情, 包括:
关于在activity中使用fragment的很强的一个特性是:根据用户的交互情况,对fragment进行添加,移除,替换,以及执行其他动作.提交给activity的每一套变化被称为一个事务,可以使用在FragmentTransaction中的 API 处理.我们也可以保存每一个事务到一个activity管理的backstack,允许用户经由fragment的变化往回导航(类似于通过 activity往后导航).
从 FragmentManager 获得一个FragmentTransaction实例 :
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
每一个事务都是同时要执行的一套变化.可以在一个给定的事务中设置你想执行的所有变化,使用诸如 add()、remove()和 replace().然后, 要给activity应用事务, 必须调用 commit().
在调用commit()之前, 你可能想调用 addToBackStack(),将事务添加到一个fragment事务的backstack. 这个back stack由activity管理, 并允许用户通过按下 BACK按键返回到前一个fragment状态.
举个例子, 这里是如何将一个fragment替换为另一个, 并在后台堆栈中保留之前的状态:
// Create new fragment and transaction
Fragment newFragment = newExampleFragment();
FragmentTransaction transaction =getFragmentManager().beginTransaction();
// Replace whatever is in thefragment_container view with this fragment,
// and add the transaction to the backstack
transaction.replace(R.id.fragment_container,newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
在这个例子中,newFragment替换了当前layout容器中的由R.id.fragment_container标识的fragment.通过调用 addToBackStack(), replace事务被保存到back stack,因此用户可以回退事务,并通过按下BACK按键带回前一个fragment.
如果添加多个变化到事务(例如add()或remove())并调用addToBackStack(),然后在你调用commit()之前的所有应用的变化会被作为一个单个事务添加到后台堆栈, BACK按键会将它们一起回退.
添加变化到 FragmentTransaction的顺序不重要, 除以下例外:
尽管Fragment被实现为一个独立于Activity的对象,并且可以在多个activity中使用,但一个给定的fragment实例是直接绑定到包含它的activity的. 特别的,fragment可以使用 getActivity() 访问Activity实例, 并且容易地执行比如在activity layout中查找一个view的任务.
View listView =getActivity().findViewById(R.id.list);
同样地,activity可以通过从FragmentManager获得一个到Fragment的引用来调用fragment中的方法, 使用findFragmentById() 或 findFragmentByTag().
ExampleFragment fragment =(ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
在一些情况下, 你可能需要一个fragment与activity分享事件. 一个好的方法是在fragment中定义一个回调的interface, 并要求宿主activity实现它.当activity通过interface接收到一个回调, 必要时它可以和在layout中的其他fragment分享信息.
例如, 如果一个新的应用在activity中有2个fragment – 一个用来显示文章列表(framgent A), 另一个显示文章内容(fragment B) – 然后 framgent A必须告诉activity何时一个list item被选中,然后它可以告诉fragmentB去显示文章.
在这个例子中, OnArticleSelectedListener 接口在fragment A中声明:
public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
}
然后fragment的宿主activity实现 OnArticleSelectedListener 接口, 并覆写 onArticleSelected() 来通知fragment B,从fragment A到来的事件.为了确保宿主activity实现这个接口, fragment A的 onAttach() 回调方法(当添加fragment到activity时由系统调用) 通过将作为参数传入onAttach()的Activity做类型转换来实例化一个OnArticleSelectedListener实例.
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 implementOnArticleSelectedListener");
}
}
...
}
如果activity没有实现接口, fragment会抛出 ClassCastException 异常. 正常情形下,mListener成员会保持一个到activity的OnArticleSelectedListener实现的引用, 因此fragment A可以通过调用在OnArticleSelectedListener接口中定义的方法分享事件给activity.例如, 如果fragment A是一个 ListFragment的子类, 每次用户点击一个列表项, 系统调用在fragment中的onListItemClick(),然后后者调用 onArticleSelected() 来分配事件给activity.
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Append the clicked item's row ID with the content provider Uri
Uri noteUri =ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
// Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
...
}
传给 onListItemClick() 的 id 参数是被点击的项的行ID, activity(或其他fragment)用来从应用的 ContentProvider 获取文章.
你的fragment可以通过实现 onCreateOptionMenu() 提供菜单项给activity的选项菜单(以此类推, Action Bar也一样).为了使这个方法接收调用,无论如何, 你必须在 onCreate() 期间调用 setHasOptionsMenu() 来指出fragment愿意添加item到选项菜单(否则, fragment将接收不到对 onCreateOptionsMenu()的调用).
随后从fragment添加到Option菜单的任何项,都会被追加到现有菜单项的后面.当一个菜单项被选择, fragment也会接收到 对 onOptionsItemSelected() 的回调.也可以在你的fragment layout中通过调用registerForContextMenu() 注册一个view来提供一个环境菜单.当用户打开环境菜单, fragment接收到一个对 onCreateContextMenu() 的调用.当用户选择一个项目, fragment接收到一个对onContextItemSelected() 的调用.
注意: 尽管你的fragment会接收到它所添加的每一个菜单项被选择后的回调, 但实际上当用户选择一个菜单项时, activity会首先接收到对应的回调.如果activity的on-item-selected回调函数实现并没有处理被选中的项目, 然后事件才会被传递到fragment的回调.
这个规则适用于选项菜单和环境菜单.
管理fragment的生命周期, 大多数地方和管理activity生命周期很像.和activity一样, fragment可以处于3种状态:
Resumed
在运行中的activity中fragment可见.
Paused
另一个activity处于前台并拥有焦点, 但是这个fragment所在的activity仍然可见(前台activity局部透明或者没有覆盖整 个屏幕).
Stopped
要么是宿主activity已经被停止, 要么是fragment从activity被移除但被添加到后台堆栈中.
停止状态的fragment仍然活着(所有状态和成员信息被系统保持着). 然而, 它对用户不再可见, 并且如果activity被干掉, 他也会被干掉.
其对应关系图如下:
fragment生命周期的流程, 以及宿主activity对它的影响,在图3中显示.在这个图中,可以看到activity依次的每个状态是如何决定fragment可能接收到的回调方法.例如, 当activity接收到它的onCreate(),activity中的fragment接收到最多是onActivityCreated().
一旦activity到达了resumed状态, 你可以自由地在activity添加和移除fragment.因此,仅当activity处于resumed状态时, fragment的生命周期才可以独立变化.
无论如何, 当activity离开resumed状态,fragment再次被activity的推入它自己的生命周期过程.
因篇幅问题不能全部显示,请点此查看更多更全内容