`

andorid中的fragment详细介绍及应用

阅读更多

andorid中的fragment详细介绍及应用

android Fragments详解一:概述

 Fragmentactivity的界面中的一部分或一种行为。你可以把多个Fragment们组合到一个activity中来创建一个多面界面并且你可以在多个activity中重用一个Fragment。你可以把Fragment认为模块化的一段activity,它具有自己的生命周期,接收它自己的事件,并可以在activity运行时被添加或删除。

Fragment不能独立存在,它必须嵌入到activity中,而且Fragment的生命周期直接受所在的activity的影响。例如:当activity暂停时,它拥有的所有的Fragment们都暂停了,当activity销毁时,它拥有的所有Fragment们都被销毁。然而,当activity运行时(在onResume()之后,onPause()之前),你可以单独地操作每个Fragment,比如添加或删除它们。当你在执行上述针对Fragment的事务时,你可以将事务添加到一个棧中,这个栈被activity管理,栈中的每一条都是一个Fragment的一次事务。有了这个栈,就可以反向执行Fragment的事务,这样就可以在Fragment级支持返回键(向后导航)。

当向activity中添加一个Fragment时,它须置于ViewGroup控件中,并且需定义Fragment自己的界面。你可以在layoutxml文件中声明Fragment,元素为:<fragment>;也可以在代码中创建Fragment,然后把它加入到ViewGroup控件中。然而,Fragment不一定非要放在activity的界面中,它可以隐藏在后台为actvitiy工作。

本章描述如何使用fragment,包括fragment在加入activity的后退棧中时如何保持自己的状态,如何与activity以及其它fragment们共享事件,如何显示在activity的动作栏,等等。

设计哲学

Android3.0开始引入fragment,主要是为了支持更动态更灵活的界面设计,比如在平板上的应用。平板机上拥有比手机更大的屏幕空间来组合和交互界面组件们。Fragment使你在做那样的设计时,不需应付view树中复杂的变化。通过把activitylayout分成fragment,你可以在activity运行时改变它的样子,并且可以在activity的后退栈中保存这些改变。

例如:写一个读新闻的程序,可以用一个fragment显示标题列表,另一个fragment显示选中标题的内容,这两个fragment都在一个activity上,并排显示。那么这两个fragment都有自己的生命周期并响应自己感兴趣的事件。于是,不需再像手机上那样用一个activity显示标题列表,用另一个activity显示新闻内容;现在可以把两者放在一个activity上同时显示出来。如下图:



Fragment必须被写成可重用的模块。因为fragment有自己的layout,自己进行事件响应,拥有自己的生命周期和行为,所以你可以在多个activity中包含同一个Fragment的不同实例。这对于让你的界面在不同的屏幕尺寸下都能给用户完美的体验尤其重要。比如你可以在程序运行于大屏幕中时启动包含很多fragmentactivity,而在运行于小屏幕时启动一个包含少量fragmentactivity

举个例子--还是刚才那个读新闻的程序-当你检测到程序运行于大屏幕时,启动activityA,你将标题列表和新闻内容这两个fragment都放在activityA中;当检测到程序运行于小屏幕时,还是启动activityA,但此时A中只有标题列表fragment,当选中一个标题时,activityA启动activityBB中含有新闻内容fragment

 

android Fragments详解二:创建Fragment

创建Fragment

    要创建fragment,必须从FragmentFragment的派生类派生出一个类。Fragment的代码写起来有些像activity。它具有跟activity一样的回调方法,比如 onCreate(),onStart(),onPause()onStop()。实际上,如果你想把老的程序改为使用fragment,基本上只需要把activity的回调方法的代码移到fragment中对应的方法即可。

通常需要实现以上生命周期函数:

onCreate():

当创建fragment时系统调用此方法。在其中你必须初始化fragment的基础组件们。可参考activity的说明。

onCreateView()

系统在fragment要画自己的界面时调用(在真正显示之前)此方法。这个方法必须返回framentlayout的根控件。如果这个fragment不提供界面,那它应返回null

onPause()

不废话了,跟activity一样。

大多数程序应最少对fragment实现这三个方法。当然还有其它几个回调方法可应该按情况实现之。所有的生命周期回调函数在操控fragment的生命周期一节中有详细讨论。

下图为fragment的生命周期(它所在的activity处于运行状态)。已经画得很明白了,不用再解释了吧?



还有几个现成的fragemtn的派生类,你可能需要从它们派生,如下所列:

DialogFragment

显示一个浮动的对话框。使用这个类创建对话框是替代activity创建对话框的最佳选择.因为你可以把fragmentdialog放入到activity的返回栈中,使用户能再返回到这个对话框。

ListFragment

显示一个列表控件,就像ListActivity类,它提供了很多管理列表的方法,比如onListItemClick()方法响应click事件。

PreferenceFragment

显示一个由Preference对象组成的列表,与PreferenceActivity相同。它用于为程序创建设置”activity

 Fragments详解三:实现Fragment的界面


fragment添加用户界面

    fragment一般作为activity的用户界面的一部分,把它自己的layout嵌入到activitylayout中。    一个

    要为fragment提供layout,你必须实现onCreateView()回调方法,然后在这个方法中返回一个View对象,这个对象是fragmentlayout的根。

    注:如果你的fragment是从ListFragment中派生的,就不需要实现onCreateView()方法了,因为默认的实现已经为你返回了ListView控件对象。

    要从onCreateView()方法中返回layout对象,你可以从layoutxml中生成layout对象。为了帮助你这样做,onCreateView()提供了一个LayoutInflater对象。

举例:以下代码展示了一个Fragment的子类如何从layoutxml文件example_fragment.xml中生成对象。

publicstaticclassExampleFragmentextendsFragment{
   @Override
  publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){
       //Inflate the layout for this fragment
       returninflater.inflate(R.layout.example_fragment,container,false);
   }
}

    onCreateView()参数中的container是存放fragmentlayoutViewGroup对象。savedInstanceState参数是一个Bundle,跟activityonCreate()Bundle差不多,用于状态恢复。但是fragmentonCreate()中也有Bundle参数,所以此处的Bundle中存放的数据与onCreate()中存放的数据还是不同的。至于详细信息,请参考操控fragment的生命周期一节。

Inflate()方法有三个参数:

1layout的资源ID

2存放fragmentlayoutViewGroup

3布尔型数据表示是否在创建fragmentlayout期间,把layout附加到container上(在这个例子中,因为系统已经把layout插入到container中了,所以值为false,如果为true会导至在最终的layout中创建多余的ViewGroup(这句我看不明白,但我翻译的应该没错))。

现在你看到如何为fragment创建layout了,下面讲述如何把它添加到activity中。

fragment添加到activity

    一般情况下,fragment把它的layout作为activitiyloyout的一部分合并到activity中,有两种方法将一个fragment添加到activity中:

方法一:在activitylayoutxml文件中声明fragment

    如下代码,一个activity中包含两个fragment

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <fragmentandroid:name="com.example.news.ArticleListFragment"
           android:id="@+id/list"
           android:layout_weight="1"
           android:layout_width="0dp"
          android:layout_height="match_parent"/>
   <fragmentandroid:name="com.example.news.ArticleReaderFragment"
           android:id="@+id/viewer"
           android:layout_weight="2"
           android:layout_width="0dp"
          android:layout_height="match_parent"/>
</LinearLayout>

<fragment>中声明一个fragment

    当系统创建上例中的layout时,它实例化每一个fragment,然后调用它们的onCreateView()方法,以获取每个fragmentlayout。系统把fragment返回的view对象插入到<fragment>元素的位置,直接代替<fragment>元素。

    注:每个fragment都需要提供一个ID,系统在activity重新创建时用它来恢复fragment们,你也可以用它来操作fragment进行其它的事物,比如删除它。有三种方法给fragment提供ID

1 android:id属性赋一个数字。

2 android:tag属性赋一个字符串。

3如果你没有使用上述任何一种方法,系统将使用fragment的容器的ID

方法二:在代码中添加fragment到一个ViewGroup

     这种方法可以在运行时,把fragment添加到activitylayout中。你只需指定一个要包含fragmentViewGroup

    为了完成fragment的事务(比如添加,删除,替换等),你必须使用FragmentTransaction的方法。你可以从activity获取到FragmentTransaction,如下:

FragmentManagerfragmentManager =getFragmentManager()
FragmentTransactionfragmentTransaction =fragmentManager.beginTransaction();

    然后你可以用add()方法添加一个fragment,它有参数用于指定容纳fragmentViewGroup。如下:

ExampleFragmentfragment =newExampleFragment();
fragmentTransaction.add(R.id.fragment_container,fragment);
fragmentTransaction.commit();

    Add()的第一个参数是容器ViewGroup,第二个是要添加的fragment。一旦你通过FragmentTransactionfragment做出了改变,你必须调用方法commit()提交这些改变。

不仅在无界面的fragment中,在有界面的fragment中也可以使用tag来作为为一标志,这样在需要获取fragment对象时,要调用findFragmentTag()

添加一个没有界面的fragment

    上面演示了如何添加fragment来提供界面,然而,你也可以使用fragmentactivity提供后台的行为而不用显示fragment的界面。

    要添加一个没有界面的fragment,需在activity中调用方法add(Fragment,String)(它支持用一个唯一的字符串做为fragment”tag”,而不是viewID)。这样添加的fragment由于没有界面,所以你在实现它时不需调用实现onCreateView()方法。

    使用tag字符串来标识一个fragment并不是只能用于没有界面的fragment上,你也可以把它用于有界面的fragment上,但是,如果一个fragment没有界面,tag字符串将成为它唯一的选择。获取以tag标识的fragment,需使用方法findFragmentByTab()

android Fragments详解四:管理fragment

要管理fragment们,需使用FragmentManager,要获取它,需在activity中调用方法getFragmentManager()

你可以用FragmentManager来做以上事情:



1使用方法findFragmentById()findFragmentByTag(),获取activity中已存在的fragment们。

2使用方法popBackStack()activity的后退栈中弹出fragment们(这可以模拟后退键引发的动作)。

3用方法addOnBackStackChangedListerner()注册一个侦听器以监视后退栈的变化。

更多关于以上方法的信息,请参考“FragmentManager”文档。

就像前面章节所演示的,你还可以使用FragmentManager打开一个FragmentTransaction来执行fragment的事务,比如添加或删除fragment

执行Fragment的事务

activity中使用fragment的一个伟大的好处是能跟据用户的输入对fragment进行添加、删除、替换以及执行其它动作的能力。你提交的一组fragment的变化叫做一个事务。事务通过FragmentTransaction来执行。你还可以把每个事务保存在activity的后退栈中,这样就可以让用户在fragment变化之间导航(跟在activity之间导航一样)。

你可以通过FragmentManager来取得FragmentTransaction的实例,如下:

FragmentManagerfragmentManager=getFragmentManager();
FragmentTransactionfragmentTransaction=fragmentManager.beginTransaction();

一个事务是在同一时刻执行的一组动作(很像数据库中的事务)。你可以用add(),remove(),replace()等方法构成事务,最后使用commit()方法提交事务。

在调用commint()之前,你可以用addToBackStack()把事务添加到一个后退栈中,这个后退栈属于所在的activity。有了它,就可以在用户按下返回键时,返回到fragment们执行事务之前的状态。

如下例:演示了如何用一个fragment代替另一个fragment,同时在后退栈中保存被代替的fragment的状态。

//Create new fragment and transaction
FragmentnewFragment=newExampleFragment();
FragmentTransactiontransaction=getFragmentManager().beginTransaction();

//Replace whatever is in the fragment_container view with thisfragment,
//and add the transaction to the backstack
transaction.replace(R.id.fragment_container,newFragment);
transaction.addToBackStack(null);

//Commit the transaction
transaction.commit();

解释:newFragment代替了控件IDR.id.fragment_container所指向的ViewGroup中所含的任何fragment。然后调用addToBackStack(),此时被代替的fragment就被放入后退栈中,于是当用户按下返回键时,事务发生回溯,原先的fragment又回来了。

如果你向事务添加了多个动作,比如多次调用了add(),remove()等之后又调用了addToBackStack()方法,那么所有的在commit()之前调用的方法都被作为一个事务。当用户按返回键时,所有的动作都被反向执行(事务回溯)。

事务中动作的执行顺序可随意,但要注意以下两点:

1你必须最后调用commit()

2如果你添加了多个fragment,那么它们的显示顺序跟添加顺序一至(后显示的覆盖前面的)。

如果你在执行的事务中有删除fragment的动作,而且没有调用addToBackStack(),那么当事务提交时,那些被删除的fragment就被销毁了。反之,那些fragment就不会被销毁,而是处于停止状态。当用户返回时,它们会被恢复。

密技:对于fragment事务,你可以应用动画。在commit()之前调用setTransition()就行。――一般银我不告诉他哦。

但是,调用commit()后,事务并不会马上执行。它会在activityUI线程(其实就是主线程)中等待直到线程能执行的时候才执行(废话)。如果必要,你可以在UI线程中调用executePendingTransactions()方法来立即执行事务。但一般不需这样做,除非有其它线程在等待事务的执行。

警告:你只能在activity处于可保存状态的状态时,比如running中,onPause()方法和onStop()方法中提交事务,否则会引发异常。这是因为fragment的状态会丢失。如果要在可能丢失状态的情况下提交事务,请使用commitAllowingStateLoss()

android Fragments详解五:activity通讯

activity通讯

尽管fragment的实现是独立于activity的,可以被用于多个activity,但是每个activity所包含的是同一个fragment的不同的实例。

Fragment可以调用getActivity()方法很容易的得到它所在的activity的对象,然后就可以查找activity中的控件们(findViewById())。例如:

ViewlistView =getActivity().findViewById(R.id.list);

同样的,activity也可以通过FragmentManager的方法查找它所包含的frament们。例如:

ExampleFragment fragment=(ExampleFragment)getFragmentManager().findFragmentById(R.id.example_fragment

activity响应fragment的事件

有时,你可能需要fragmentactivity共享事件。一个好办法是在fragment中定义一个回调接口,然后在activity中实现之。

例如,还是那个新闻程序的例子,它有一个activityactivity中含有两个fragmentfragmentA显示新闻标题,fragmentB显示标题对应的内容。fragmentA必须在用户选择了某个标题时告诉activity,然后activity再告诉fragmentBfragmentB就显示出对应的内容(为什么这么麻烦?直接fragmentA告诉fragmentB不就行了?也可以啊,但是你的fragment就减少了可重用的能力。现在我只需把我的事件告诉宿主,由宿主决定如何处置,这样是不是重用性更好呢?)。如下例,OnArticleSelectedListener接口在fragmentA中定义

public static class FragmentA extends ListFragment{
   ...
   //Container Activity must implement this interface
   public interface OnArticleSelectedListener{
       public void onArticleSelected(Uri articleUri);
   }
   ...
}

然后activity实现接口OnArticleSelectedListener,在方法onArticleSelected()中通知fragmentB。当fragment添加到activity中时,会调用fragment的方法onAttach(),这个方法中适合检查activity是否实现了OnArticleSelectedListener接口,检查方法就是对传入的activity的实例进行类型转换,如下所示:

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 implement OnArticleSelectedListener");
       }
   }
   ...
}

如果activity没有实现那个接口,fragment抛出ClassCastException异常。如果成功了,mListener成员变量保存OnArticleSelectedListener的实例。于是fragmentA就可以调用mListener的方法来与activity共享事件。例如,如果fragmentA是一个ListFragment,每次选中列表的一项时,就会调用fragmentAonListItemClick()方法,在这个方法中调用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,另一个fragment用这个ID来从程序的ContentProvider中取得标题的内容。

Fragments详解六:处理fragement的生命周期

把条目添加到动作栏

你的fragment们可以向activity的菜单(按Manu键时出现的东西)添加项,同时也可向动作栏(界面中顶部的那个区域)添加条目,这都需通过实现方法onCreateOptionManu()来完成。

你从fragment添加到菜单的任何条目,都会出现在现有菜单项之后。Fragment之后可以通过方法onOptionsItemSelected()来响应自己的菜单项被选择的事件。

你也可以在fragemnt中注册一个view来提供快捷菜单(上下文菜单)。当用户要打开快捷菜单时,fragmentonCreateContextMenu()方法会被调用。当用户选择其中一项时,fragemntonContextItemSelected()方法会被调用。

注:尽管你的fragment可以分别收到它所添加的菜单项的选中事件,但是activity才是第一个接收这些事件的家伙,只有当activity对某个事件置之不理时,fragment才能接收到这个事件,对于菜单和快捷菜单都是这样。



处理fragement的生命周期

管理fragment的生命周期有些像管理activity的生命周期。Fragment可以生存在三种状态:

Resumed:

Fragment在一个运行中的activity中并且可见。

Paused:

另一个activity处于最顶层,但是fragment所在的activity并没有被完全覆盖(顶层的activity是半透明的或不占据整个屏幕)。

Stoped:

Fragment不可见。可能是它所在的activity处于stoped状态或是fragment被删除并添加到后退栈中了。此状态的fragment仍然存在于内存中。

同样类似于activity,你可以把fragment的状态保存在一个Bundle中,在activityrecreated时就需用到这个东西。你可以在onSaveInstanceState()方法中保存状态并在onCreate()onCreateView()onActivityCreated()中恢复,关于更多的保存状态的信息,请参考Activitys章节。

FragmentActivity的生命周期中最大的不同就是存储到后退栈中的过程。Activity是在停止时自动被系统压入停止栈,并且这个栈是被系统管理的;而fragment是被压入activity所管理的一个后退栈,并且只有你在删除fragment后并明确调用addToBackStack()方法时才被压入。

然而,管理fragment的生命周期与管理activity的生命周期极其相似。你所需要去思考的是activity的生命周期如何影响fragment的生命周期。

android Fragments详解七:fragement示例

下例中实验了上面所讲的所有内容。此例有一个activity,其含有两个fragment。一个显示莎士比亚剧的播放曲目,另一个显示选中曲目的摘要。此例还演示了如何跟据屏幕大小配置fragment

activity创建layout

 

1         @Override 

2         protectedvoid onCreate(Bundle savedInstanceState) { 

3            super.onCreate(savedInstanceState); 

4           

5            setContentView(R.layout.fragment_layout); 

6         } 


activitylayoutxml文档源码打印

7         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

8             android:orientation="horizontal" 

9             android:layout_width="match_parent" android:layout_height="match_parent"> 

10        

11          <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" 

12                  android:id="@+id/titles" android:layout_weight="1" 

13                  android:layout_width="0px" android:layout_height="match_parent" /> 

14        

15          <FrameLayout android:id="@+id/details" android:layout_weight="1"  

16                  android:layout_width="0px" android:layout_height="match_parent" 

17                  android:background="?android:attr/detailsElementBackground" /> 

18        

19      </LinearLayout> 


系统在activity加载此layout时初始化TitlesFragment(用于显示标题列表),TitlesFragment的右边是一个FrameLayout,用于存放显示摘要的fragment,但是现在它还是空的,fragment只有当用户选择了一项标题后,摘要fragment才会被放到FrameLayout中。然而,并不是所有的屏幕都有足够的宽度来容纳标题列表和摘要。所以,上述layout只用于横屏,现把它存放于ret/layout-land/fragment_layout.xml

之外,当用于竖屏时,系统使用下面的layout,它存放于ret/layout/fragment_layout.xml

20      <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 

21          android:layout_width="match_parent" android:layout_height="match_parent"> 

22          <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" 

23                  android:id="@+id/titles" 

24                  android:layout_width="match_parent" android:layout_height="match_parent" /> 

25      </FrameLayout> 

这个layout只包含TitlesFragment。这表示当使用竖屏时,只显示标题列表。当用户选中一项时,程序会启动一个新的activity去显示摘要,而不是加载第二个fragment

下一步,你会看到Fragment类的实现。第一个是TitlesFragment,它从ListFragment派生,大部分列表的功能由ListFragment提供。

当用户选择一个Title时,代码需要做出两种行为,一种是在同一个activity中显示创建并显示摘要fragment,另一种是启动一个新的activity

26      public static class TitlesFragment extends ListFragment { 

27          boolean mDualPane; 

28          int mCurCheckPosition = 0; 

29        

30          @Override 

31          public void onActivityCreated(Bundle savedInstanceState) { 

32              super.onActivityCreated(savedInstanceState); 

33        

34              // Populate list with our static array of titles. 

35              setListAdapter(new ArrayAdapter<String>(getActivity(), 

36                      android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES)); 

37        

38              // Check to see if we have a frame in which to embed the details 

39              // fragment directly in the containing UI. 

40              View detailsFrame = getActivity().findViewById(R.id.details); 

41              mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; 

42        

43              if (savedInstanceState != null) { 

44                  // Restore last state for checked position. 

45                  mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); 

46              } 

47        

48              if (mDualPane) { 

49                  // In dual-pane mode, the list view highlights the selected item. 

50                  getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

51                  // Make sure our UI is in the correct state. 

52                  showDetails(mCurCheckPosition); 

53              } 

54          } 

55        

56          @Override 

57          public void onSaveInstanceState(Bundle outState) { 

58              super.onSaveInstanceState(outState); 

59              outState.putInt("curChoice", mCurCheckPosition); 

60          } 

61        

62          @Override 

63          public void onListItemClick(ListView l, View v, int position, long id) { 

64              showDetails(position); 

65          } 

66        

67          /**

68           * Helper function to show the details of a selected item, either by

69           * displaying a fragment in-place in the current UI, or starting a

70           * whole new activity in which it is displayed.

71           */ 

72          void showDetails(int index) { 

73              mCurCheckPosition = index; 

74        

75              if (mDualPane) { 

76                  // We can display everything in-place with fragments, so update 

77                  // the list to highlight the selected item and show the data. 

78                  getListView().setItemChecked(index, true); 

79        

80                  // Check what fragment is currently shown, replace if needed. 

81                  DetailsFragment details = (DetailsFragment) 

82                          getFragmentManager().findFragmentById(R.id.details);  

83                  if (details == null || details.getShownIndex() != index) { 

84                      // Make new fragment to show this selection. 

85                      details = DetailsFragment.newInstance(index); 

86        

87                      // Execute a transaction, replacing any existing fragment 

88                      // with this one inside the frame. 

89                      FragmentTransaction ft = getFragmentManager().beginTransaction(); 

90                      ft.replace(R.id.details, details); 

91                      ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 

92                      ft.commit(); 

93                  } 

94        

95              } else { 

96                  // Otherwise we need to launch a new activity to display 

97                  // the dialog fragment with selected text. 

98                  Intent intent = new Intent(); 

99                  intent.setClass(getActivity(), DetailsActivity.class); 

100               intent.putExtra("index", index); 

101               startActivity(intent); 

102           } 

103       } 


第二个fragmentDetailsFragment显示被选择的Title的摘要:
源码打印

104   public static class DetailsFragment extends Fragment { 

105       /**

106        * Create a new instance of DetailsFragment, initialized to

107        * show the text at 'index'.

108        */ 

109       public static DetailsFragment newInstance(int index) { 

110           DetailsFragment f = new DetailsFragment(); 

111     

112           // Supply index input as an argument. 

113           Bundle args = new Bundle(); 

114           args.putInt("index", index); 

115           f.setArguments(args); 

116     

117           return f; 

118       } 

119     

120       public int getShownIndex() { 

121           return getArguments().getInt("index", 0); 

122       } 

123     

124       @Override 

125       public View onCreateView(LayoutInflater inflater, ViewGroup container, 

126               Bundle savedInstanceState) { 

127           if (container == null) { 

128               // We have different layouts, and in one of them this 

129               // fragment's containing frame doesn't exist.  The fragment 

130               // may still be created from its saved state, but there is 

131               // no reason to try to create its view hierarchy because it 

132               // won't be displayed.  Note this is not needed -- we could 

133               // just run the code below, where we would create and return 

134               // the view hierarchy; it would just never be used. 

135               return null; 

136           } 

137     

138           ScrollView scroller = new ScrollView(getActivity()); 

139           TextView text = new TextView(getActivity()); 

140           int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 

141                   4, getActivity().getResources().getDisplayMetrics()); 

142           text.setPadding(padding, padding, padding, padding); 

143           scroller.addView(text); 

144           text.setText(Shakespeare.DIALOGUE[getShownIndex()]); 

145           return scroller; 

146       } 

147   } 


如果当前的layout没有R.id.detailsView(它被用于DetailsFragment的容器),那么程序就启动DetailsActivity来显示摘要。下面是DetailsActivity,它只是简单地嵌入DetailsFragment来显示摘要。

148   public static class DetailsActivity extends Activity { 

149     

150       @Override 

151       protected void onCreate(Bundle savedInstanceState) { 

152           super.onCreate(savedInstanceState); 

153     

154           if (getResources().getConfiguration().orientation 

155                   == Configuration.ORIENTATION_LANDSCAPE) { 

156               // If the screen is now in landscape mode, we can show the 

157               // dialog in-line with the list so we don't need this activity. 

158               finish(); 

159               return; 

160           } 

161     

162           if (savedInstanceState == null) { 

163               // During initial setup, plug in the details fragment. 

164               DetailsFragment details = new DetailsFragment(); 

165               details.setArguments(getIntent().getExtras()); 

166               getFragmentManager().beginTransaction().add(android.R.id.content, details).commit(); 

167           } 

168       } 

169   } 


注意这个activity在检测到是竖屏时会结束自己,于是主activity会接管它并显示出TitlesFragmentDetailsFragment。这可以在用户在竖屏时显示在TitleFragment,但用户旋转了屏幕,使显示变成了横屏。

 

协调与activity生命周期的关系

Activity直接影响它所包含的fragment的生命周期,所以对activity的某个生命周期方法的调用也会产生对fragment相同方法的调用。例如:当activityonPause()方法被调用时,它所包含的所有的fragment们的onPause()方法都会被调用。

Fragmentactivity还要多出几个生命周期回调方法,这些额外的方法是为了与activity的交互而设立,如下:

onAttach()

fragment被加入到activity时调用(在这个方法中可以获得所在的activity)。

onCreateView()

activity要得到fragmentlayout时,调用此方法,fragment在其中创建自己的layout(界面)

onActivityCreated()

activityonCreated()方法返回后调用此方法。

onDestroyView()

fragmentlayout被销毁时被调用。

onDetach()

fragment被从activity中删掉时被调用。

一旦activity进入resumed状态(也就是running状态),你就可以自由地添加和删除fragment了。因此,只有当activityresumed状态时,fragment的生命周期才能独立的运转,其它时候是依赖于activity的生命周期变化的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics