把条目添加到动作栏

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

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

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

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

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

MainActivity:

  1. @Override
  2. protectedvoid onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.fragment_layout);
  5. }

Layout.xml:

  1. <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. <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
  5. android:id="@+id/titles" android:layout_weight="1"
  6. android:layout_width="0px" android:layout_height="match_parent" />
  7. <FrameLayout android:id="@+id/details" android:layout_weight="1"
  8. android:layout_width="0px" android:layout_height="match_parent"
  9. android:background="?android:attr/detailsElementBackground" />
  10. </LinearLayout>

系统在activity加载此layout时初始化TitlesFragment(用于显示标题列表),TitlesFragment的右边是一个FrameLayout,用于存放显示摘要的fragment,但是现在它还是空的,fragment只有当用户选择了一项标题后,摘要fragment才会被放到FrameLayout中。

然而,并不是所有的屏幕都有足够的宽度来容纳标题列表和摘要。所以,上述layout只用于横屏,现把它存放于ret/layout-land/fragment_layout.xml。

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

  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>

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

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

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

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

第二个fragment,DetailsFragment显示被选择的Title的摘要:

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

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

下面是DetailsActivity,它只是简单地嵌入DetailsFragment来显示摘要。

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

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

【JAVA】鉴于plaincopy

Android Fragment详解(六):Fragement示例的更多相关文章

  1. Android Fragment详解

    一.什么是Fragment Android在3.0中引入了fragments的概念,主要目的是用在大屏幕设备上--例如平板电脑上,支持更加动态和灵活的UI设计.平板电脑的屏幕要比手机的大得多,有更多的 ...

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

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

  3. android——fragment详解

    在android开发过程中,如果使用到了导航栏.那么不可避免的就需要使用fragment来处理界面.闲着没事,就详解一下Framgent的使用方法吧. 难得写一次.本人 shoneworn shone ...

  4. Android Fragment 详解(一)

    Android从3.0开始引入fragment,主要是为了支持更动态更灵活的界面设计,比如在平板上的应用.平板机上拥有比手机更大的屏幕空间来组合和交互界面组件们.Fragment使你在做那样的设计时, ...

  5. Android Fragment详解(二):Fragment创建及其生命周期

    Fragments的生命周期 每一个fragments 都有自己的一套生命周期回调方法和处理自己的用户输入事件. 对应生命周期可参考下图: 创建片元(Creating a Fragment) To c ...

  6. Android Fragment详解(一):概述

    Fragment是activity的界面中的一部分或一种行为.你可以把多个Fragment们组合到一个activity中来创建一个多面界面并且你可以在多个activity中重用一个Fragment.你 ...

  7. Android Fragment详解(三): 实现Fragment的界面

    为fragment添加用户界面: Fragment一般作为activity的用户界面的一部分,把它自己的layout嵌入到activity的layout中. 一个 要为fragment提供layout ...

  8. Android Fragment 详解(未完...)

    版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Fragment 文中如有纰漏,欢迎大家留言指出. 之前写过一篇关于 Fragment 生命周期的文章 ...

  9. Android Fragment详解(五):Fragment与Activity通讯

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

随机推荐

  1. JavaScripts学习日记——DOM SAX JAXP DEMO4J XPath

    今日关键词: XML解析器 DOM SAX JAXP DEMO4J XPath XML解析器 1.解析器概述 什么是解析器 XML是保存数据的文件,XML中保存的数据也需要被程序读取然后使用.那么程序 ...

  2. Menu( 菜单)

    一. 加载方式菜单组件通常用于快捷菜单,在加载方式上,通过 class 或 JS 进行设置为菜单组件.然后,再通过 JS 事件部分再响应.//class 加载方式<div id="bo ...

  3. MongoDB-C# Driver账户密码登录问题

    MongoDb在3.0之后添加了SCRAM-SHA-1,用户验证模式.添加的用户,默认登录协议也是这个. 在登陆的时候就要选择使用这种方式登录.有的gui客户端的登录验证方式还是MONGODB-CR. ...

  4. C# 前台线程与后台线程区别

    using System; using System.Drawing; using System.Windows.Forms; using System.Threading; namespace Wi ...

  5. Dom4j 添加 / 更新 / 删除 XML

    1.获得文档 /** *1.获得解析流 *2.解析XML */ 2.添加 /** *1.获取父元素 *2.创建元素 *3.创建属性并添加到元素中 *4.元素添加到根节点 */ 3.更新 /** *1. ...

  6. myeclipseb笔记(4):拷贝文件的相应配置

    在MyEclipse中,经常需要用到拷贝工程文件,但是直接拷贝的话,就会出现访问不了的情况,如下: 原文件learn/StudManage/login.jsp,访问: 拷贝工程,改名,访问: 就出现了 ...

  7. poj3254状压DP入门

    G - 状压dp Crawling in process... Crawling failed Time Limit:2000MS     Memory Limit:65536KB     64bit ...

  8. 理解jquery的.on()方法

    jquery在的.on()方法用来给元素绑定事件处理函数的,我经常用在两个地方: 给未来的元素绑定事件:我总是这样用:$(document).on('click','#div1',function() ...

  9. [转]关于Chrome不能登录和同步的解决方法

    原帖地址:http://tieba.baidu.com/p/3086127792?pn=1 在本机的hosts文件(C:\Windows\System32\drivers\etc)里加入下面内容: # ...

  10. NET Core依赖注入解读&使用Autofac替代实现

    NET Core依赖注入解读&使用Autofac替代实现 标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. ...