1. 继承关系

java.lang.Object

|__android.app.Fragment

实现接口:ComponentCallbacks2 View.OnCreateContextMenuListener

引入版本:API Level 11

已知的子类:

DialogFragment、ListFragment、PreferenceFragment、WebViewFragment

2. 类概要

一个Fragment是应用程序的用户界面或行为的一个片段,它能够被放置在一个Activity中。通过FragmentManager对象来实现与Fragment对象的交互,能够通过Activity.getFragmentManager()方法和Fragment.getFragmentManager()方法来获取FragmentManager对象。

Fragment类有着广泛的应用,它的核心是代表了一个正在较大的Activity中运行的特俗的操作或界面。Fragment对象跟它所依附的Activity对象是紧密相关的,并且不能被分开使用。尽管Fragment对象定义了它们自己的生命周期,但是这个生命周期要依赖与它所在的Activity:如果该Activity被终止,那么它内部的Fragment是不能被启动的;当Activity被销毁时,它内部的所有Fragment对象都会被销毁。

所有的Fragment子类都必须包含一个公共的空的构造器。在需要的时候,Framework会经常重新实例化Fragment类,在特殊的状态恢复期间,需要能够找到这个构造器来实例化Fragment类。如果空的构造器无效,那么在状态恢复期间会导致运行时异常发生。

较旧的平台

尽管Fragment API是在HONEYCOMB版本中被引入的,但是通过FragmentActivity也能够在较旧的平台上使用该API。

声明周期

尽管Fragment对象的生命周期要依附于它所在的Activity对象,但是它也有自己标准的活动周期,它包含了基本的活动周期方法,如onResume(),但是同时也包含了与Activity和UI交互相关的重要方法。

显示Fragment时(跟用户交互)要调用的核心的生命周期方法如下:

1. 把Fragment对象跟Activity关联时,调用onAttach(Activity)方法;

2. Fragment对象的初始创建时,调用onCreate(Bundle)方法;

3. onCreateView(LayoutInflater, ViewGroup, Bundle)方法用于创建和返回跟Fragment关联的View对象;

4. onActivityCreate(Bundle)方法会告诉Fragment对象,它所依附的Activity对象已经完成了Activity.onCreate()方法的执行;

5. onStart()方法会让Fragment对象显示给用户(在包含该Fragment对象的Activity被启动后);

6. onResume()会让Fragment对象跟用户交互(在包含该Fragment对象的Activity被启恢复后)。

Fragment对象不再使用时,要反向回调的方法:

1. 因为Fragment对象所依附的Activity对象被挂起,或者在Activity中正在执行一个修改Fragment对象的操作,而导致Fragment对象不再跟用户交互时,系统会调用Fragment对象的onPause()方法;

2. 因为Fragment对象所依附的Activity对象被终止,或者再Activity中正在执行一个修改Fragment对象的操作,而导致Fragment对象不再显示给用户时,系统会调用Fragment对象的onStop()方法。

3. onDestroyView()方法用于清除跟Fragment中的View对象关联的资源;

4. Fragment对象的状态被最终清理完成之后,要调用onDestroy()方法;

5. 在Fragment对象不再跟它依附的Activity关联的时候,onDetach()方法会立即被调用。

布局

Fragment对象能够被用于应用程序的布局,它会让代码的模块化更好,并且针对Fragment所运行的屏幕,让用户界面的调整更加容易。例如,一个简单的由项目列表和项目明细表示所组成的程序。

一个Activity的布局XML能够包含要嵌入到布局内部的Fragment实例的<fragment>标签。例如,下例中在布局中嵌入了一个Fragment对象:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent" /></FrameLayout>

以下是布局被安装到Activity中的通常方法:

@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.fragment_layout);}

依赖ListFragment对象,要显示列表的标题是相当简单的。要注意的是,点击一个列表项的实现,会依赖当前Activity的布局,它既可以创建一个新的Fragment用于显示该项目的明细,也可以启动一个新的Activity用于显示项目的明细。

public static class TitlesFragment extends ListFragment { boolean mDualPane; int mCurCheckPosition = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Populate list with our static array of titles.setListAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES)); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFrame = getActivity().findViewById(R.id.details);mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; if (savedInstanceState != null) { // Restore last state for checked position.mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); } if (mDualPane) { // In dual-pane mode, the list view highlights the selected item.getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Make sure our UI is in the correct state.showDetails(mCurCheckPosition); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState);outState.putInt("curChoice", mCurCheckPosition); } @Override public void onListItemClick(ListView l, View v, int position, long id) {showDetails(position); } /*** Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
void showDetails(int index) {mCurCheckPosition = index; if (mDualPane) { // We can display everything in-place with fragments, so update // the list to highlight the selected item and show the data.getListView().setItemChecked(index, true); // Check what fragment is currently shown, replace if needed. DetailsFragment details = (DetailsFragment)getFragmentManager().findFragmentById(R.id.details); if (details == null || details.getShownIndex() != index) { // Make new fragment to show this selection.details = DetailsFragment.newInstance(index); // Execute a transaction, replacing any existing fragment // with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction();ft.replace(R.id.details, details);ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);ft.commit(); } } else { // Otherwise we need to launch a new activity to display // the dialog fragment with selected text. Intent intent = new Intent();intent.setClass(getActivity(), DetailsActivity.class);intent.putExtra("index", index);startActivity(intent); } }}

明细Fragment对象只会显示所选项目的详细文本字符串,它是基于内置在应用中的一个字符数组的索引来获取的:

public static class DetailsFragment extends Fragment { /*** Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
     */
public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle();args.putInt("index", index);f.setArguments(args); return f; } public int getShownIndex() { return getArguments().getInt("index", 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { // We have different layouts, and in one of them this // fragment's containing frame doesn't exist.  The fragment // may still be created from its saved state, but there is // no reason to try to create its view hierarchy because it // won't be displayed.  Note this is not needed -- we could // just run the code below, where we would create and return // the view hierarchy; it would just never be used. return null; } ScrollView scroller = new ScrollView(getActivity()); TextView text = new TextView(getActivity()); int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources().getDisplayMetrics());text.setPadding(padding, padding, padding, padding);scroller.addView(text);text.setText(Shakespeare.DIALOGUE[getShownIndex()]); return scroller; }}

在用户点击标题的情况下,在当前的Activity中没有明细容器,因此标题Fragment的点击事件代码会启动一个新的显示明细Fragment的Activity:

public static class DetailsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity.finish(); return; } if (savedInstanceState == null) { // During initial setup, plug in the details fragment. DetailsFragment details = new DetailsFragment();details.setArguments(getIntent().getExtras());getFragmentManager().beginTransaction().add(android.R.id.content, details).commit(); } }}

但是,屏幕可能足够显示标题列表和当前所选标题相关的明细。对于在横向屏幕上这样的布局,可以被放置在layout-land下面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent" /> <FrameLayout android:id="@+id/details" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent" android:background="?android:attr/detailsElementBackground" /></LinearLayout>

要注意的是,以上代码是如何调整这种可选的UI流的:标题Fragment对象被嵌入到该Activity内部的明细Fragment对象中,并且如果Fragment对象运行在一个有显示明细空间的配置环境中,那么明细Activity会由它自己来完成。

当由于配置的改变而导致Activity所持有的这些Fragment对象重启的时候,它们新的Fragment实例可以使用与之前所使用的布局不同的布局。在这种情况中,之前所有的Fragment对象依然会被实例化,并运行在新的实例中。但是任何不在跟<fragment>关联的View对象将不会再被创建,并且重isInLayout()方法中返回false。

在把Fragment的View对象绑定到父容器的时候,<fragment>标签的属性被用于控制提供给LayoutParams对象的信息,它们能够作为Fragment对象中的onInflate(Activity, AttributeSet, Bundle)方法的参数来解析。

正在实例化的Fragment对象必须要有某些类型唯一标识,以便在它的父Activity在销毁并重建的时候,能够被重新关联到之前的实例。可以使用以下方法来实现这种关联:

1. 如果没有明确的指定,则使用容器的View ID来标识;

2. 使用<fragment>元素的android:tag属性,给Fragment对象元素提供一个特定的标签名称;

3. 使用<fragment>元素的android:id属性,给Fragment对象的元素提供一个特定的标识。

Android类参考---Fragment(一)相关推荐

  1. Android类参考---Fragment(五)

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) 当Vie ...

  2. Android学习之 Fragment

    [eoe特刊]Fragment- 特刊-eoe Fragment应用的介绍 - memegood123的专栏 - 博客频道 - CSDN.NET android之Fragment(官网资料翻译) - ...

  3. Android Activity和Fragment的转场动画

    Activity转场动画 Activity的转场动画是通过overridePendingTransition(int enterAnim, int exitAnim)实现的. 这个方法是API Lev ...

  4. Android深入理解Fragment

    Fragment 目录 思维导图 概述 设计原因 基本使用 xml 声明 代码设置 添加没有 UI 的 fragment 生命周期 管理 Fragment 和执行事务 与 Activity 通信 常见 ...

  5. 【Android】保存Fragment切换状态

    [Android]保存Fragment切换状态 前言 一般频繁切换Fragment会导致频繁的释放和创建,如果Fragment比较臃肿体验就非常不好了,这里分享一个方法. 声明 欢迎转载,但请保留文章 ...

  6. Android系列之Fragment(二)----Fragment的生命周期和返回栈

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  7. android fragment传递数据,Android 两个Fragment之间传递数据实例详解

    Android 两个Fragment之间如何传递数据 FragmentA启动FragmentB,做一些选择操作后,返回FragmentA,需要把FragmentB里面选择的数据传回来.有什么办法? F ...

  8. android左右滑动fragment,Android基于ViewPager+Fragment实现左右滑屏效果的方法

    本文实例讲述了Android基于ViewPager+Fragment实现左右滑屏效果的方法.分享给大家供大家参考,具体如下: 1.xml布局模板 android:id="@+id/local ...

  9. Android基础之Fragment

    目录 前言 一.Fragment简介 二.Fragment的基础使用 1.创建Fragment 2.在Activity中加入Fragment (1)在Activity的layout.xml布局文件中静 ...

最新文章

  1. 北大「最优化:建模、算法与理论」新书, 附579页电子版与课件
  2. 干货丨2017年含金量最高的机器学习技能或知识有哪些?
  3. 百度开源其NLP主题模型工具包,文本分类等场景可直接使用L——LDA进行主题选择本质就是降维,然后用于推荐或者分类...
  4. int main(int argc,char* argv[])详解(原)
  5. SSH框架中配置log4j的方法
  6. 深度学习的三种硬件方案:ASIC,FPGA,GPU;你更看好?
  7. 美国国防部选择VMware View用于全球作战系统
  8. php 右下脚弹窗,纯js的右下角弹窗实例代码
  9. mysqldump单个库导出_初相识 | 全方位认识 sys 系统库
  10. linux6.5 安装yum,配置Centos 6.5的yum源
  11. Java ClassLoader getSystemClassLoader()方法与示例
  12. python3.0与2.x之间的区别
  13. 3.微服务:从设计到部署 --- 进程间通信
  14. 加密与解密工具大礼包 2010年新品
  15. android ts合并_ts视频合并工具安卓版
  16. ubuntu18.04安装nvidia驱动(戴尔G15_3060版本)
  17. 项目5-模板类中使用友元函数
  18. 解决Microsoft已经阻止宏运行,因为此文件的来源不受信任。
  19. 移动应用程序开发_移动应用程序开发生命周期-从开发到应用程序商店的应用程序之旅
  20. csdn博客贴代码方式

热门文章

  1. NEC学习 ---- 模块 - 带点文字链接列表
  2. 【ASP】简单Url编码和Url解码实例
  3. 字符串搜索。HOJ1530 Compound Words。
  4. Google, 请不要离开我们!
  5. Indy中判断邮件来源
  6. rstudio 导出结果_RStudio如何完美导出包含中文的图
  7. Mybatis框架中SqlSessionFactory
  8. RocketMQ消息重试机制
  9. SpringBoot集成Mybatis用法笔记
  10. 100个网络基础必备知识 ,值得收藏!