更新时间:2022-06-10 02:41:02
Fragment是Android自从3.0之后新加入的一个组件,我相信很多人都已经听说过这个组件了,但这个组件到底是个什么,如何去使用他呢,且听我讲来。
以下部分资料来自官网(官网才是王道,其他都是浮云)
一、Fragment要点
Fragment作为Activity界面的一部分组成出现
可以在一个Activity中同时出现多个Fragment,并且,一个Fragment亦可在多个Activity中使用。
在Activity运行过程中,可以添加、移除或者替换Fragment(add()、remove()、replace())
Fragment可以响应自己的输入事件,并且有自己的生命周期,当然,它们的生命周期直接被其所属的宿主activity的生命周期影响。
设计哲学
Android在3.0中引入了fragments的概念,主要目的是用在大屏幕设备上--例如平板电脑上,支持更加动态和灵活的UI设计。平板电脑的屏幕要比手机的大得多,有更多的空间来放更多的UI组件,并且这些组件之间会产生更多的交互。Fragment允许这样的一种设计,而不需要你亲自来管理 viewhierarchy的复杂变化。 通过将activity的布局分散到fragment中, 你可以在运行时修改activity的外观,并在由activity管理的back stack中保存那些变化.(http://developer.android.com/guide/topics/fundamentals/fragments.html)
例如, 一个新闻应用可以在屏幕左侧使用一个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到底是个什么东西了。
二、如何去使用一个Fragment呢
1、要创建一个fragment, 必须创建一个 Fragment 的子类 (或者继承自一个已存在的它的子类). Fragment类的代码看起来很像 Activity 。它包含了和activity类似的回调方法, 例如onCreate()、 onStart()、onPause()以及 onStop()。事实上, 如果你准备将一个现成的Android应用转换到使用fragment,可能只需简单的将代码从你的activity的回调方法分别移动到你的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); } }
<?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>
FragmentManager fragmentManager =getFragmentManager(); FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
ExampleFragment fragment = newExampleFragment(); fragmentTransaction.add(R.id.fragment_container,fragment); fragmentTransaction.commit();
FragmentManager fragmentManager =getFragmentManager(); FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();每一个事务都是同时要执行的一套变化.可以在一个给定的事务中设置你想执行的所有变化,使用诸如 add()、remove()和 replace().然后, 要给activity应用事务, 必须调用 commit().
// 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();
View listView =getActivity().findViewById(R.id.list);
ExampleFragment fragment =(ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
public static class FragmentA extends ListFragment { ... // Container Activity must implement this interface public interface OnArticleSelectedListener { public void onArticleSelected(Uri articleUri); } ... }
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"); } } ... }
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); } ... }
和activity一样, 你可以使用Bundle保持fragment的状态, 万一activity的进程被干掉,并且当activity被重新创建的时候, 你需要恢复fragment的状态时就可以用到. 你可以在fragment的 onSaveInstanceState() 期间保存状态, 并可以在 onCreate(), onCreateView() 或 onActivityCreated() 期间恢复它.
生命周期方面activity和fragment之间最重要的区别是各自如何在它的后台堆栈中储存. 在默认情况下, activity在停止后, 它会被放到一个由系统管理的用于保存activity的后台堆栈.(因此用户可以使用BACK按键导航回退到它).
然而, 仅当你在一个事务期间移除fragment时,显式调用addToBackStack()请求保存实例时,才被放到一个由宿主activity管理的后台堆栈.
另外, 管理fragment的生命周期和管理activity生命周期非常类似.因此, "managing the activitylifecycle"中的相同实践也同样适用于fragment. 你需要理解的是, activity的生命如何影响fragment的生命.
与activity生命周期的协调工作
fragment所生存的activity的生命周期,直接影响fragment的生命周期,每一个activity的生命周期的回调行为都会引起每一个fragment中类似的回调.
例如,当activity接收到onPause()时,activity中的每一个fragment都会接收到onPause().
Fragment 有一些额外的生命周期回调方法, 那些是处理与activity的唯一的交互,为了执行例如创建和销毁fragment的UI的动作. 这些额外的回调方法是:
onAttach()
当fragment被绑定到activity时被调用(Activity会被传入.).
onCreateView()
创建和fragment关联的view hierarchy时调用.
onActivityCreated()
当activity的onCreate()方法返回时被调用.
onDestroyView()
当和fragment关联的view hierarchy正在被移除时调用.
onDetach()
当fragment从activity解除关联时被调用.
fragment生命周期的流程, 以及宿主activity对它的影响,在图3中显示.在这个图中,可以看到activity依次的每个状态是如何决定fragment可能接收到的回调方法.例如, 当activity接收到它的onCreate(),activity中的fragment接收到最多是onActivityCreated().
一旦activity到达了resumed状态, 你可以***地在activity添加和移除fragment.因此,仅当activity处于resumed状态时, fragment的生命周期才可以独立变化.
无论如何, 当activity离开resumed状态,fragment再次被activity的推入它自己的生命周期过程.