最值得看的android系统fragment教程--翻译自安卓官方文档

注意:如果你是用的是V4包中的API.你需要

1.Activity必须继承FragmentActivity

2.使用getSupportFragmentManager()而不是getFragmentManager().

Fragment



Fragment代表了Activity中ui的一个独立行为,或者说一个区域.你可以在Activity中组合多个Fragment去打造多面板的ui,你也能够在多个Activity中重用同一个Fragment.你可以把Fragment想象成Activity的一个拥有独立生命周期并且可以独立的接受输入事件的模块,你也能够把它加入或移除一个正在运行的Activity(某种程度上像一个你能够在多个Activity中重用的子Activity).
Fragment 必须被嵌入一个Activity(以下称为宿主Activity)中,且Fragment的生命周期,直接被其宿主Activity所影响.比如说,当Activity进入paused状态,所有子Fragment也会paused.Activity被Destroy. 所有子Fragment也会跟着被销毁.不仅如此,当Activity正在运行(也就是resumed状态)时,你依然可以独立操纵每个单独的Fragment,例如增加和移除它们.当你增删它们的时候,你可以把它们加入一个由宿主Activity所管理的回退栈中.每个回退栈记录了你对Fragment所进行的事务.回退栈使得用户可以通过点击返回按钮返回上一个对Fragment进行的事务.
当你把一个Fragment作为你Activity的一部分增加到布局中时,它是以Activity的view中一个子View的形式存在的.你可以在Activity布局中用一个<Fragment>元素去声明一下,这样你就在Activity中插入了一个Fragment.你同样也可以在代码中将其动态添加到某个ViewGroup里面.但是这并不表示Fragment必须要成为Activity布局的一部分,你也能加入一个没有UI界面的Fragment当成”隐形工人”来使用.

这篇文档主要描述如何去使用Fragment搭建你的APP.具体包括:
1. Fragments在被加入回退栈时怎么去保持它们的状态.
2. Fragment和Activity的通信,Fragments之间的通信.
3. 怎么更好的搭配Actionbar的使用等等.



Creating a Fragment

为了创建一个Fragment,你必须创建一个类去继承Fragment(或者使用一个系统定义的Fragment的子类).这个Fragment类的代码看起来非常像Activity.它包含了一些和Activity类似的回调方法,例如 onCreate()onStart()onPause() onStop().事实上,如果你正在用Fragment重构你的app代码,你要做的仅仅是把你在Activity的回调方法里的代码搬运到Fragment的回调方法里面.

通常,你至少需要实现下列方法:

onCreate()

当系统创建Fragment的时候会回调这个方法.在你的实现方法里,你应该初始化那些Fragment中必不可少的组件,以便于当Fragment经历Paused,stoped最终resume的时候,你能保留他们.

onCreateView()

当Fragment第一次去画他的UI的时候,系统会回调这个方法.你必须在这个方法里返回你的Fragment的根布局的View实例以使系统创建Fragment的UI.如果Fragment没有界面,你就返回null.

onPause()

系统调用这个方法作为用户离开Fragment的首要标识(但是,这并不意味着Fragment被销毁).你应当在这里保存用户操作引起的参数(比如一些设置)改变.因为用户可能不会再返回了

大多数app应当给每个Fragment至少实现这里列出的三个方法,但是还有一些其他的回调函数能用来处理Fragment的各种生命周期状态.


我们也提供了几个你可能想去继承的子类,以替代Fragment基类:
DialogFragment
展示一个浮动的对话框.使用这个类去创建一个对话框是一个在Activity类中替换dialoghelper方法创建对话框的好选择,因为你能在Activity的Fragment回退栈中放入一个Fragment对话框,受Activity的管理.这样用户就可以点返回返回刚才的对话框了.
ListFragment
展示一列被adapter关联的条目,类似于listActivity.它提供了几个方法去管理一个listView.例如处理点击事件的onListItemClick()回调函数.
PreferenceFragment
用列表展示一层偏好设置,类似于 PreferenceActivity .这样你在做一些设置界面的时候就会很方便.


Adding a user interface

Fragment通常被用作Activity 界面的一部分并且向Activity提供它自己的布局.
想给Fragment提供一个布局,你必须实现oncreateView()回调方法.安卓系统会在绘制Fragment的界面的时候回调它.你对这个方法的实现,必须返回一个View实例.这个实例应该是Fragment布局的根布局.


提示:如果你的Fragment是listFragment的子类,默认实现就返回了一个listView,所以你就不必去实现了.
你可以从资源文件里inflate一个XML文件出一个View作为你的Fragment的布局,为了帮你实现这一点,oncreateView()方法提供了一个LayoutInflater给你使用.


下列代码中,Fragment的实现类从example_Fragment.xml中加载了一个布局.

[java]  view plain  copy
  1. public static class ExampleFragment extends Fragment {  
  2.     @Override  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  4.                              Bundle savedInstanceState) {  
  5.         // Inflate the layout for this Fragment  
  6.         return inflater.inflate(R.layout.example_Fragment, container, false);  
  7.     }  
  8. }  
被传入oncreateView的Container参数是在Activity布局中指定的父容器,你的Fragment应该被插入到这个container里面. 如果这个Fragment是被恢复状态的话,那么savedInstanceState参数就是一个提供了之前Fragment实例数据的数据包,.
Inflate方法接收三个参数:
1.你想inflate的资源ID
2.你将要压缩的这个布局的父布局.在这里传入container是非常重要的,这可以方便系统给你所inflate的这个布局的根布局设置由父View指定的参数.(译者注:这里不传container你的xml文件中的某些属性会失效,原因请搜索郭霖大神的博文)
3.一个用来标识inflate的这个布局是否要被附到Viewgroup(就是第二个参数)的布尔值.
现在你已经了解了怎么创建一个有布局的Fragment.

下一步,你需要把它添加到你的Activity中.



Adding a fragment to an activity

方式一:在xml文件里声明

在下面这个例子里,你能像一个普通的View一样为Fragment指定布局属性.如下例子:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="horizontal"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.     <Fragment android:name="com.example.news.ArticleListFragment"  
  7.             android:id="@+id/list"  
  8.             android:layout_weight="1"  
  9.             android:layout_width="0dp"  
  10.             android:layout_height="match_parent" />  
  11.     <Fragment android:name="com.example.news.ArticleReaderFragment"  
  12.             android:id="@+id/viewer"  
  13.             android:layout_weight="2"  
  14.             android:layout_width="0dp"  
  15.             android:layout_height="match_parent" />  
  16. </LinearLayout>  

<Fragment>中的android:name属性指定了Fragment的类名来初始化布局.
当系统创建Activity布局的时候,它会初始化每个在xml中指定的Fragment,并调用每个Fragment的oncreateView()方法来取得每个Fragment的布局.系统会将Fragment返回的View直接插入<Fragment>元素中.


提示:每个Fragment需要一个特定的标识使得系统在Activity重新启动时能用来恢复Fragment.(你也可以用来获得Fragment去做一些事务,例如移除它),有三种方式可以给Fragment提供一个ID.
1. 指定android:id属性
2. 指定android:tag属性
3. 如果你没有使用前两种,系统会使用containerView的ID.


方式二:用编程的方式将Fragment增加到现存的ViewGroup中
在你的Activity运行的任何时刻,你都能增加Fragment到你的Activity布局中.你只需要简单的指定一个用来容纳Fragment的Viewgroup.
想在你的Activity中使用Fragment事务,例如增加和移除的事务,你必须使用来自FragmentTransaction的API.你可以使用如下代码从你的Activity中得到一个FragmentTransaction的实例:

[java]  view plain  copy
  1. FragmentManager FragmentManager = getFragmentManager()  
  2. FragmentTransaction FragmentTransaction = FragmentManager.beginTransaction();  
你能使用add()方法增加一个Fragment,同时说明他要被插入到哪个View中.例如:

[java]  view plain  copy
  1. ExampleFragment Fragment = new ExampleFragment();  
  2. FragmentTransaction.add(R.id.Fragment_container, Fragment);  
  3. FragmentTransaction.commit();  
第一个传入add()函数的参数是Fragment将要插入的Viewgroup对象,使用资源ID来指定,第二个参数就是要增加的Fragment.一旦你使用FragmentTraction做出一些事务,你必须调用commit()函数来使它生效.

Adding a fragment to an activity

上面的例子展示了怎么增加一个用来展示UI的Fragment到你的Activity中.你也能使用Fragment做一些后台操作,而不用显示不必要的UI.

想要增加一个没有UI的Fragment,在Activity中使用add(Fragment,string)方法增加这个Fragment(提供一个”tag”字符串,而不是资源ID).但是因为它没有和Activity中的某个View关联,它不会接收oncreateView的返回值.所以你不必实现这个方法.

提供tag字符串并不是只有不含UI的Fragment才可以,你也能给一个有UI的Fragment提供tag.但是如果这个Fragment没有UI,那么这个tag就是它的唯一标识.

你稍后想找到这个Fragment的话,你需要去使用findFragmentByTag()方法.

FragmentRetainInstance.java文件里有一个没有UI的Fragment的例子.这个文件在SDKmanager里面可以下载到,下载后的文件路径是<sdk_root>/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java.


Managing Fragments

想在你的Activity里面管理Fragments,你需要使用FragmentManager类.使用Activity的getFragmentManager()方法可以得到它.

使用FragmentManager可以做到的事情包括:

1.使用findFragmentById()方法得到一个Activity中已经存在的Fragment(提供了UI).

或者findFragmentByTag()(没有UI).

2.从回退栈中将Fragment弹出,使用popBackStack()方法.(模拟一个用户返回的操作)

3.使用addOnBackStackChangeListener()给回退栈注册一个监听器.

更多的其他方法,请查阅FragmentManager的API文档.

还有在前一个部分提到过的,你也能用FragmentManager类去开始一个Fragmenttransaction.以便于你执行一个增加或者移除的事务.

Performing Fragment Transactions

在Activity中使用Fragments的一大特点就是你可以增加,删除,替换以及对他们进行一些其他操作,以响应用户交互.你提交给Activity的每一套操作都被称为事务.你可以使用Fragmenttransaction的API执行一些操作.你也能保存每个事务到被Activity管理的回退栈中,使得用户可以导航回退一些Fragment的操作.

你能像这样得到Fragmentmanager的实例:

[java]  view plain  copy
  1. FragmentManager FragmentManager = getFragmentManager();  
  2. FragmentTransaction FragmentTransaction = FragmentManager.beginTransaction();  

每个事务是你想执行的一连串的操作.你可以准备所有你会使用诸如add(),remove()和replace()执行的事务.然后调用commit()方法,将事务提交给Activity去执行.

调用commit()方法之前,你也可能想去调用addtoBackstack()方法把你的事务加入到一个由Activity管理的Fragment的事务的回退栈中.这个由Activity管理的回退栈允许用户通过实体返回键返回上一个Fragment.

下面这个例子演示了怎么将你的Fragment换成另一个,并且在回退栈中保存之前的状态.

[java]  view plain  copy
  1. // Create new Fragment and transaction  
  2. Fragment newFragment = new ExampleFragment();  
  3. FragmentTransaction transaction = getFragmentManager().beginTransaction();  
  4.   
  5. // Replace whatever is in the Fragment_container view with this Fragment,  
  6. // and add the transaction to the back stack  
  7. transaction.replace(R.id.Fragment_container, newFragment);  
  8. transaction.addToBackStack(null);  
  9.   
  10. // Commit the transaction  
  11. transaction.commit();  

上例中,  newFragment 替换了当前布局中用 R.id.Fragment_container这个ID标识的Fragment.

通过调用addtobackstack(),这个替换的事务被回退栈保存,所以用户能够用返回键返回被替换之前的fragment.

如果做出了多个改变在一个事务中(比如同时调了add()和remove())然后调用addtobackstack().那么在你调用commit()方法之前所做的所有改变都会被当成一个整体存到回退栈中.这时候返回键会一次性返回到所有这些改变之前的状态.

你把操作加入Fragmenttransaction的顺序无所谓,但是你要注意:

1.   你必须调用commit()方法.

2.   如果你在一个容器中加入了多个Fragment,你加入它们的顺序决定了它们的显示层次.

如果你没有调用addtobackstack()方法那么当你执行移除Fragment的操作时,你commit之后,这个Fragment就会被销毁,不能够再返回这个Fragment.然而如果你调用了,那么它就会进入stop状态,并且用户返回时将会恢复.

提示:如果你想加上Fragment切换动画,commit之前调用settransiton()方法.

调用commit()方法并不会立即执行你的事务.它被安排你的UI线程有空闲执行的时候去执行.如果必要的话,我们也提供了executePendingTransactions() 方法让你的UI线程能立即去执行commit()的事务.除非这个事务依赖于其他线程的一些工作,否则这么做没有太大必要.(译者注:因为延迟很短,可以忽略不计)

注意:你只能在Activity”保存状态”(用户离开Activity)之前提交你的事务.否则将会抛出异常.这是因为如果Activity需要被销毁的话,Activity的状态可能会丢失.

如果即使丢失了状态也要执行,你可以使用commitAllowingStateLoss().

Communicating with the Activity

尽管Fragment是作为一个独立于Activity实现的,但是作为一个给定的Fragment的实例还是被直接绑在一个容纳它的Activity上.

具体的来说,Fragment内部能用getActivity()方法获得Activity实例,并且可以非常容易的在Activity中做一些例如findview的操作.

  
  
[java] view plain copy
  1. <pre name="code" class="java">View listView = getActivity().findViewById(R.id.list);  
 

相同的,你的Activity能通过某个Fragment的实例调用Fragment的方法.从Fragmentmanager中的findFragmentById()  findFragmentByTag()方法你能获得Fragment的引用.

  
  
[java] view plain copy
  1. ExampleFragment Fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_Fragment);  

Creatingevent callbacks to the Activity

在一些情况下,你可能需要Fragment和Activity共享事件.这样做的一个好办法就是在Fragment中定义一个回调接口,让Activity去实现它.当Activity从回调接口中收到事件通知时,它就可以把这些信息和其他Fragment分享,如果有必要的话.

例如,一个新闻app的某个Activity中有两个Fragment----一个用来展示新闻列表(Fragment A),一个用来展示新闻内容(Fragment B).那么Fragment A必须告诉Activity某个新闻项目被点击了,Activity再去通知Fragment B,让Fragment B去展示这篇新闻.

下面这个例子中,  OnArticleSelectedListener 接口定义在Fragment A中:

[java]  view plain  copy
  1. public static class FragmentA extends ListFragment {  
  2.     ...  
  3.     // Container Activity must implement this interface  
  4.     public interface OnArticleSelectedListener {  
  5.         public void onArticleSelected(Uri articleUri);  
  6.     }  
  7.     ...  
  8. }  

然后Activity去实现这个监听接口,并且复写了 onArticleSelected() 方法去告知Fragment B一些FragmentA 中发生的事件.为了保证宿主Activity实现了这个接口.Fragment A的onattach()回调方法(系统把Fragment增加到Activity的时候回调此方法)强转了传入onattach中的Activity实例.并用这个Activity实例去初始化了   OnArticleSelectedListener    接口的一个实例.

[java]  view plain  copy
  1. <span style="font-size:18px;">public static class FragmentA extends ListFragment {  
  2.     OnArticleSelectedListener mListener;  
  3.     ...  
  4.     @Override  
  5.     public void onAttach(Activity Activity) {  
  6.         super.onAttach(Activity);  
  7.         try {  
  8.             mListener = (OnArticleSelectedListener) Activity;  
  9.         } catch (ClassCastException e) {  
  10.             throw new ClassCastException(Activity.toString() + " must implement OnArticleSelectedListener");  
  11.         }  
  12.     }  
  13.     ...  
  14. }</span>  


如果这个Activity没有实现接口,那么Fragment就会抛出强转异常.如果成功的话,mListener成员变量就持有了一个实现了回调接口的Activity的引用.这样FragmentA就可以通过调用接口中的方法和Activity共享一些事件了.例如,如果Fragment A是一个列表Fragment.它就可以在每次列表被点击的时候调用 OnArticleSelectedListener接口中定义的onArticleSelected() 方法去通知Activity.

[java]  view plain  copy
  1. public static class FragmentA extends ListFragment {  
  2.     OnArticleSelectedListener mListener;  
  3.     ...  
  4.     @Override  
  5.     public void onListItemClick(ListView l, View v, int position, long id) {  
  6.         // Append the clicked item's row ID with the content provider Uri  
  7.         Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);  
  8.         // Send the event and Uri to the host Activity  
  9.         mListener.onArticleSelected(noteUri);  
  10.     }  
  11.     ...  
  12. }  

Addingitems to the Action Bar

你的Fragment能够通过实现 onCreateOptionsMenu()方法给Activity的选项菜单增加菜单项(同样也包括ActionBar)

为了使你实现的这个方法被调用,你必须在onCreate()的时候调用setHasOptionsMenu()方法来告诉系统这个Fragment要给菜单里加东西,否则你的onCreateOptionsMenu()方法不会被调用.

你的Fragment往菜单里添加的任何条目都会添加到现存的菜单列表里.菜单项被选择的时候,Fragment的onOptionsItemSelected()方法也会被回调.

通过调用registerForContextMenu()方法,你也依然能在你的Fragment布局中注册一个View以提供一个ContextMenu.当用户打开ContextMenu,你的onCreateContextMenu()方法将被回调.当用户点击ContextMenu的菜单项,Fragment的onContextItemSelected()方法将被回调.

注意:尽管你的Fragment收到来自它自己添加的菜单项的on-item-selected回调,当用户点击时,它的Activity仍然是首先收到它自己的回调函数.如果Activity没有处理此事件,那么事件才会被传递到Fragment的回调.对于Options Menucontext menus都是这样

关于菜单的更多信息,请查看菜单和actionbar的开发指南.



Handling the Fragment Lifecycle

Fragment的生命周期和Activity的很像.就像Activity一样,一个Fragment能存在三种状态.

Resumed

      Fragment在一个运行的Activity中可见

Paused

      另一个Activity在前台并且获得了焦点,但是Fragment所在的Activity仍然可见.(前台的Activity部分透明或者没有覆盖整个屏幕)

 Stopped

Fragment不可见,原因有:

1.   宿主Activity也被停止了.

2.   Fragment被移除但是加入了回退栈

一个停止的Fragment仍然存活,系统保留了它的所有状态和成员信息.但是它已经不再可见并且如果Activity被销毁,它也会被销毁.

同样的,你能用bundle去保存Fragment的状态.如果那样的话,你能保存状态当Fragment的onSaveInstanceState()回调的时候,并且在onCreate()onCreateView(), oronActivityCreated()的时候恢复他们.想知道更过关于保存状态的信息,请查看Activity的文档.

Activity和Fragment生命周期最大的不同就是他们是如何被存储进各自的回退栈中的.当Activity进入停止状态时,它会默认被加入一个由系统管理的回退栈中(所以用户才能用返回键返回上一个Activity).而相关的Fragment想加入回退栈中只有当你移除它时显式的调用addToBackStack()方法.

除了这个,管理Fragment的生命周期非常像管理Activity的生命周期.你需要额外注意的就是Activity的生命周期是如何影响Fragment的.

注意:如果你在Fragment里需要获得context对象,你可以调用getActivity()方法.但是需要小心的去使用这个方法.只有你的Fragment被附到Activity上的时候,你才能得到正确的结果.当你的Fragment还没有附上的时候,或在生命周期结束时已经被从Activity剥离了,那么getActivity()将返回null.


Coordinatingwith the Activity lifecycle

Activity的生命周期会直接影响Fragment的生命周期,几乎每个Activity生命周期回调方法Fragment都会有一个与之类似的返回.例如,当Activity收到onPause()回调是,其中的每个Fragment都会收到onPause()回调.

Fragment有很少的额外生命周期回调.即便这样,这几个额外的回调还是处理了许多和Activity的特殊相互作用,例如创建或销毁Fragment的UI.这些额外的方法就是:

onAttach()

      当Fragment和Activity发生联系的时候调用(Activity会被传进来)

onCreateView()

      调用这个方法去建立和Fragment相关联的视图层

onActivityCreated()

      当Activity的oncreate方法返回时

onDestroyView()

      当Fragment相应的UI被销毁时

onDetach()

      当Fragment和Activity断开联系时调用

Fragment的生命流程图,以及它是如何被其宿主Activity所影响的,已经展示在图3中.在这张图中你能看到一个连续的Activity的状态是如何决定每个Fragment的回调函数何时调用的.例如,当Activity收到他的onCreate()回调,它当中的Fragment收到不仅仅是onActivityCreated()回调  


一旦Activity进入Resume的状态,你能自由的增加和移除Fragments到Activity中.因此,只有当Activity进入Resume状态的时候,Fragment的生命周期才能独立改变.

即便如此,当Activity离开恢复状态的时候,Fragment才会再一次被Activity推动它的生命周期历程.


Example

为了兼顾上述文档中提到的所有内容,这里是一个单Activity使用双Fragment来创建一个双面板布局的例子.下面将要展示的这个Activity包含一个用来展示莎士比亚戏剧的标题的Fragment和一个用来展示从标题栏选择之后的喜剧内容的Fragment.它也提供了Fragment和Activity如何适应横竖屏的解决方案.

 

 

加载MainActivity的代码

  
  
[java] view plain copy
  1. <span style="font-size:18px;">@Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.   
  5.     setContentView(R.layout.Fragment_layout);  
  6. }</span>  

布局文件 Fragment_layout.xml如下

[html]  view plain  copy
  1. <span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="horizontal"  
  3.     android:layout_width="match_parent" android:layout_height="match_parent">  
  4.   
  5.     <Fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"  
  6.             android:id="@+id/titles" android:layout_weight="1"  
  7.             android:layout_width="0px" android:layout_height="match_parent" />  
  8.   
  9.     <FrameLayout android:id="@+id/details" android:layout_weight="1"  
  10.             android:layout_width="0px" android:layout_height="match_parent"  
  11.             android:background="?android:attr/detailsElementBackground" />  
  12.   
  13. </LinearLayout></span>  


使用这个布局,系统会在Activity加载布局的同时初始化TitlesFragment,与此同时,一个framlayout占据了屏幕右边的空间,但是什么都没有.正如你将要看见的,直到用户从选择了某个选项之后,一个Fragment才被插入到这个FrameLayout中.

[html]  view plain  copy
  1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <Fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"  
  4.             android:id="@+id/titles"  
  5.             android:layout_width="match_parent" android:layout_height="match_parent" />  
  6. </FrameLayout>  


但是并不是所有的屏幕都宽到能并排显示这两个Fragment.所以上面这个布局res/layout-land/Fragment_layout.xml仅仅适用于横屏的时候.

因此当屏幕是竖屏的时候,系统就会使用保存在res/layout/Fragment_layout.xml:的布局.

[html]  view plain  copy
  1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <Fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"  
  4.             android:id="@+id/titles"  
  5.             android:layout_width="match_parent" android:layout_height="match_parent" />  
  6. </FrameLayout>  

这个布局仅仅包含 TitlesFragment.这意味着,当设备在竖屏的时候,只有戏剧的列表是可见的.所以,当用户在竖屏下点击某个列表项的时候.app就会开启一个新的Activity来展示戏剧内容,而不是加载第二个Fragment.

下一步示范了Fragment类的实现.首先是TitlesFragment类,展示了莎士比亚的歌剧标题.这个Fragment是 ListFragment的子类.它处理了列表的工作.

当你仔细阅读以下代码的时候,你会注意到当用户点击列表项时,可能有两种情况,这取决于这两个布局中哪个是激活状态,它有可能会增加一个新布局,或者开启一个新的Activity.

[java]  view plain  copy
  1. public static class TitlesFragment extends ListFragment {  
  2.     boolean mDualPane;  
  3.     int mCurCheckPosition = 0;  
  4.   
  5.     @Override  
  6.     public void onActivityCreated(Bundle savedInstanceState) {  
  7.         super.onActivityCreated(savedInstanceState);  
  8.   
  9.         // Populate list with our static array of titles.  
  10.         setListAdapter(new ArrayAdapter<String>(getActivity(),  
  11.                 android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));  
  12.   
  13.         // Check to see if we have a frame in which to embed the details  
  14.         // Fragment directly in the containing UI.  
  15.         View detailsFrame = getActivity().findViewById(R.id.details);  
  16.         mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;  
  17.   
  18.         if (savedInstanceState != null) {  
  19.             // Restore last state for checked position.  
  20.             mCurCheckPosition = savedInstanceState.getInt("curChoice"0);  
  21.         }  
  22.   
  23.         if (mDualPane) {  
  24.             // In dual-pane mode, the list view highlights the selected item.  
  25.             getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);  
  26.             // Make sure our UI is in the correct state.  
  27.             showDetails(mCurCheckPosition);  
  28.         }  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onSaveInstanceState(Bundle outState) {  
  33.         super.onSaveInstanceState(outState);  
  34.         outState.putInt("curChoice", mCurCheckPosition);  
  35.     }  
  36.   
  37.     @Override  
  38.     public void onListItemClick(ListView l, View v, int position, long id) {  
  39.         showDetails(position);  
  40.     }  
  41.   
  42.     /** 
  43.      * Helper function to show the details of a selected item, either by 
  44.      * displaying a Fragment in-place in the current UI, or starting a 
  45.      * whole new Activity in which it is displayed. 
  46.      */  
  47.     void showDetails(int index) {  
  48.         mCurCheckPosition = index;  
  49.   
  50.         if (mDualPane) {  
  51.             // We can display everything in-place with Fragments, so update  
  52.             // the list to highlight the selected item and show the data.  
  53.             getListView().setItemChecked(index, true);  
  54.   
  55.             // Check what Fragment is currently shown, replace if needed.  
  56.             DetailsFragment details = (DetailsFragment)  
  57.                     getFragmentManager().findFragmentById(R.id.details);  
  58.             if (details == null || details.getShownIndex() != index) {  
  59.                 // Make new Fragment to show this selection.  
  60.                 details = DetailsFragment.newInstance(index);  
  61.   
  62.                 // Execute a transaction, replacing any existing Fragment  
  63.                 // with this one inside the frame.  
  64.                 FragmentTransaction ft = getFragmentManager().beginTransaction();  
  65.                 if (index == 0) {  
  66.                     ft.replace(R.id.details, details);  
  67.                 } else {  
  68.                     ft.replace(R.id.a_item, details);  
  69.                 }  
  70.                 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);  
  71.                 ft.commit();  
  72.             }  
  73.   
  74.         } else {  
  75.             // Otherwise we need to launch a new Activity to display  
  76.             // the dialog Fragment with selected text.  
  77.             Intent intent = new Intent();  
  78.             intent.setClass(getActivity(), DetailsActivity.class);  
  79.             intent.putExtra("index", index);  
  80.             startActivity(intent);  
  81.         }  
  82.     }  
  83. }  

第二个Fragment展示了从TitlesFragment中选择的戏剧的内容.

[java]  view plain  copy
  1. public static class DetailsFragment extends Fragment {  
  2.     /** 
  3.      * Create a new instance of DetailsFragment, initialized to 
  4.      * show the text at 'index'. 
  5.      */  
  6.     public static DetailsFragment newInstance(int index) {  
  7.         DetailsFragment f = new DetailsFragment();  
  8.   
  9.         // Supply index input as an argument.  
  10.         Bundle args = new Bundle();  
  11.         args.putInt("index", index);  
  12.         f.setArguments(args);  
  13.   
  14.         return f;  
  15.     }  
  16.   
  17.     public int getShownIndex() {  
  18.         return getArguments().getInt("index"0);  
  19.     }  
  20.   
  21.     @Override  
  22.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  23.             Bundle savedInstanceState) {  
  24.         if (container == null) {  
  25.             // We have different layouts, and in one of them this  
  26.             // Fragment's containing frame doesn't exist.  The Fragment  
  27.             // may still be created from its saved state, but there is  
  28.             // no reason to try to create its view hierarchy because it  
  29.             // won't be displayed.  Note this is not needed -- we could  
  30.             // just run the code below, where we would create and return  
  31.             // the view hierarchy; it would just never be used.  
  32.             return null;  
  33.         }  
  34.   
  35.         ScrollView scroller = new ScrollView(getActivity());  
  36.         TextView text = new TextView(getActivity());  
  37.         int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
  38.                 4, getActivity().getResources().getDisplayMetrics());  
  39.         text.setPadding(padding, padding, padding, padding);  
  40.         scroller.addView(text);  
  41.         text.setText(Shakespeare.DIALOGUE[getShownIndex()]);  
  42.         return scroller;  
  43.     }  
  44. }  

回顾 TitlesFragment类,如果用户点击了某个列表项并且当前布局中不包含R.id.detailsview(包含DetailsFragment的布局),那么Activity就会开启DetailsActivity  Activity类来展示列表项的内容.

下面是在竖屏上用来替代DetailsFragment  DetailsActivity类.

[java]  view plain  copy
  1. public static class DetailsActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.   
  7.         if (getResources().getConfiguration().orientation  
  8.                 == Configuration.ORIENTATION_LANDSCAPE) {  
  9.             // If the screen is now in landscape mode, we can show the  
  10.             // dialog in-line with the list so we don't need this Activity.  
  11.             finish();  
  12.             return;  
  13.         }  
  14.   
  15.         if (savedInstanceState == null) {  
  16.             // During initial setup, plug in the details Fragment.  
  17.             DetailsFragment details = new DetailsFragment();  
  18.             details.setArguments(getIntent().getExtras());  
  19.             getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();  
  20.         }  
  21.     }  
  22. }  

需要注意的是如果配置为横屏,那么这个Activity就会结束它自己让main Activity接管,然后在旁边展示.这会发生在如果用户开启Activity的时候是竖屏,但是之后旋转为横屏.

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值