原文网址:http://www.cnblogs.com/mengdd/archive/2013/01/08/2851368.html

Fragment

  Android是在Android 3.0 (API level 11)开始引入Fragment的。

  可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity运行的时候可以加载或者移除Fragment模块。

  可以把Fragment设计成可以在多个Activity中复用的模块。

  当开发的应用程序同时适用于平板电脑和手机时,可以利用Fragment实现灵活的布局,改善用户体验。

  如图:

Fragment的生命周期

  因为Fragment必须嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是密切相关的。

  如果Activity是暂停状态,其中所有的Fragment都是暂停状态;如果Activity是stopped状态,这个Activity中所有的Fragment都不能被启动;如果Activity被销毁,那么它其中的所有Fragment都会被销毁。

  但是,当Activity在活动状态,可以独立控制Fragment的状态,比如加上或者移除Fragment。

  当这样进行fragment transaction(转换)的时候,可以把fragment放入Activity的back stack中,这样用户就可以进行返回操作。

Fragment的使用相关

  使用Fragment时,需要继承Fragment或者Fragment的子类(DialogFragment, ListFragment, PreferenceFragment, WebViewFragment),所以Fragment的代码看起来和Activity的类似。

 

使用Support Library

  Support Library是一个提供了API库函数的JAR文件,这样就可以在旧版本的Android上使用一些新版本的APIs。

  比如android-support-v4.jar.它的完整路径是:

  <sdk>/extras/android/support/v4/android-support-v4.jar.

  它就提供了Fragment的APIs,使得在Android 1.6 (API level 4)以上的系统都可以使用Fragment。

  为了确定没有在旧版本系统上使用新版本的APIs,需要如下导入语句:

  import android.support.v4.app.Fragment;

  import android.support.v4.app.FragmentManager;

  同时应该将上述的包拷入libs项目下的libs文件夹,然后在项目的Properties中添加:右键单击项目,选Properties,左边选Java Build Path,然后Add External JARs…,添加android-support-v4.jar.

  当创建包含Fragment的Activity时,如果用的是Support Library,那么继承的就应该是FragmentActivity而不是Activity。

 

必须实现的三个回调函数

  onCreate()

  系统在创建Fragment的时候调用这个方法,这里应该初始化相关的组件,一些即便是被暂停或者被停止时依然需要保留的东西。

  onCreateView()

  当第一次绘制Fragment的UI时系统调用这个方法,必须返回一个View,如果Fragment不提供UI也可以返回null。

  注意,如果继承自ListFragment,onCreateView()默认的实现会返回一个ListView,所以不用自己实现。

  onPause()

  当用户离开Fragment时第一个调用这个方法,需要提交一些变化,因为用户很可能不再返回来。

 

实现Fragment的UI

  提供Fragment的UI,必须实现onCreateView()方法。

  假设Fragment的布局设置写在example_fragment.xml资源文件中,那么onCreateView()方法可以如下写:

  

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);
}
}

  onCreateView()中container参数代表该Fragment在Activity中的父控件;savedInstanceState提供了上一个实例的数据。

  inflate()方法的三个参数:

  第一个是resource ID,指明了当前的Fragment对应的资源文件;

  第二个参数是父容器控件;

  第三个布尔值参数表明是否连接该布局和其父容器控件,在这里的情况设置为false,因为系统已经插入了这个布局到父控件,设置为true将会产生多余的一个View Group。

 

把Fragment加入Activity

  当Fragment被加入Activity中时,它会处在对应的View Group中。

  Fragment有两种加载方式:一种是在Activity的layout中使用标签<fragment>声明;另一种方法是在代码中把它加入到一个指定的ViewGroup中。

  另外,Fragment它可以并不是Activity布局中的任何一部分,它可以是一个不可见的部分。这部分内容先略过。

加载方式1:通过Activity的布局文件将Fragment加入Activity

  在Activity的布局文件中,将Fragment作为一个子标签加入即可。

  如:

<?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>

  其中android:name属性填上你自己创建的fragment的完整类名。

  当系统创建这个Activity的布局文件时,系统会实例化每一个fragment,并且调用它们的onCreateView()方法,来获得相应fragment的布局,并将返回值插入fragment标签所在的地方。

  有三种方法为Fragment提供ID:

  android:id属性:唯一的id

  android:tag属性:唯一的字符串

  如果上面两个都没提供,系统使用容器view的ID。

 

加载方式2:通过编程的方式将Fragment加入到一个ViewGroup中

  当Activity处于Running状态下的时候,可以在Activity的布局中动态地加入Fragment,只需要指定加入这个Fragment的父View Group即可。

  首先,需要一个FragmentTransaction实例: 

FragmentManager fragmentManager = getFragmentManager()

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

  (注,如果import android.support.v4.app.FragmentManager;那么使用的是:FragmentManager fragmentManager = getSupportFragmentManager();)

  

  之后,用add()方法加上Fragment的对象:

ExampleFragment fragment = new ExampleFragment();

fragmentTransaction.add(R.id.fragment_container, fragment);

fragmentTransaction.commit();

  其中第一个参数是这个fragment的容器,即父控件组。

  最后需要调用commit()方法使得FragmentTransaction实例的改变生效。

实例

  练习的例子:

  写一个类继承自Fragment类,并且写好其布局文件(本例中是两个TextView),在Fragment类的onCreateView()方法中加入该布局。

  之后用两种方法在Activity中加入这个fragment:

  第一种是在Activity的布局文件中加入<fragment>标签;

  第二种是在Activity的代码中使用FragmentTransaction的add()方法加入fragment。

  贴出代码:

  自己定义的fragment类: 

ExampleFragment.java

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ExampleFragment extends Fragment
{

//三个一般必须重载的方法
@Override
public void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("ExampleFragment--onCreate");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
System.out.println("ExampleFragment--onCreateView");
return inflater.inflate(R.layout.example_fragment_layout, container, false);

}

@Override
public void onPause()
{
// TODO Auto-generated method stub
super.onPause();
System.out.println("ExampleFragment--onPause");
}

@Override
public void onResume()
{
// TODO Auto-generated method stub
super.onResume();
System.out.println("ExampleFragment--onResume");
}

@Override
public void onStop()
{
// TODO Auto-generated method stub
super.onStop();
System.out.println("ExampleFragment--onStop");
}

}

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class ExampleFragment extends Fragment
{ //三个一般必须重载的方法
@Override
public void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("ExampleFragment--onCreate");
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
System.out.println("ExampleFragment--onCreateView");
return inflater.inflate(R.layout.example_fragment_layout, container, false); } @Override
public void onPause()
{
// TODO Auto-generated method stub
super.onPause();
System.out.println("ExampleFragment--onPause");
} @Override
public void onResume()
{
// TODO Auto-generated method stub
super.onResume();
System.out.println("ExampleFragment--onResume");
} @Override
public void onStop()
{
// TODO Auto-generated method stub
super.onStop();
System.out.println("ExampleFragment--onStop");
} }

  fragment的布局文件:

example_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/num1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/num2"
/>

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/num1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/num2"
/> </LinearLayout>

  主Activity:

LearnFragment.java

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class LearnFragment extends FragmentActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn_fragment);

//在程序中加入Fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.linear, fragment);
fragmentTransaction.commit();
}

}

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction; public class LearnFragment extends FragmentActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn_fragment); //在程序中加入Fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.linear, fragment);
fragmentTransaction.commit();
} }

  Activity的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn1"
/> <fragment
android:name="com.example.learningfragment.ExampleFragment"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn2"
/> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn3"
/>
</LinearLayout> </LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn1"
/> <fragment
android:name="com.example.learningfragment.ExampleFragment"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn2"
/> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn3"
/>
</LinearLayout> </LinearLayout>

  运行结果如下:

  可以看到第二种方式加入fragment的时候,指定了父容器(一个线性布局)的id,其中已经有一个Button 3,所以fragment加在其后。

 

参考资源

  Fragment类文档:

  http://developer.android.com/reference/android/app/Fragment.html

  Training:Building a Dynamic UI with Fragments

  http://developer.android.com/training/basics/fragments/index.html

  Fragments Develop Guide:

  http://developer.android.com/guide/components/fragments.html

【转】Android Fragment 基本介绍--不错的更多相关文章

  1. Android Fragment的介绍与使用(案例Demo)

    应用场景: 众所了解Android上的界面展示都是通过Activity实现的,可是Activity也有它的局限性,相同的界面在手机上显示可能非常好看,在平板上就未必了.为了让界面能够在平板上更好地展示 ...

  2. Android Fragment 基本介绍

    Fragment 源码:http://www.jinhusns.com/Products/Download/?type=xcj Android是在Android 3.0 (API level 11)开 ...

  3. Android Fragment 基本介绍[转]

    Fragment Android是在Android 3.0 (API level 11)开始引入Fragment的. 可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的 ...

  4. [原]Android Fragment 入门介绍

    Fragment Fragment 产生,优点,用途,使用方法简介 1 Fragmeng简介 自从Android 3.0中引入fragments 的概念,根据词海的翻译可以译为:碎片.片段.其上的是为 ...

  5. Android Fragment 实例

    Fragment是Android honeycomb 3.0新增的概念,在Android——Fragment介绍.Android Fragment使用.Android FragmentManage F ...

  6. Android Fragment 简单实例

    Android上的界面展示都是通过Activity实现的.Activity实在是太经常使用了.我相信大家都已经很熟悉了,这里就不再赘述. 可是Activity也有它的局限性,相同的界面在手机上显示可能 ...

  7. 【Android自学日记】【转】Android Fragment 真正的完全解析(下)

    上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Frag ...

  8. Android Fragment使用(四) Toolbar使用及Fragment中的Toolbar处理

    Toolbar作为ActionBar使用介绍 本文介绍了在Android中将Toolbar作为ActionBar使用的方法. 并且介绍了在Fragment和嵌套Fragment中使用Toolbar作为 ...

  9. Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复

    Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状 ...

随机推荐

  1. mysql case when then else end 用法

    select case when 判断条件 then 输出结果  else 输出结果 end from table

  2. portal开发"下拉框"“日期框”查询要怎么配置

    下面的这些是我今天的成果! 总的来说是一步一步摸索出来的!还是等感谢超哥的耐心指导,犯了一些错误! 1.比如在wd配置文件中中写id=“check_it_two”,在java中写成 checki_it ...

  3. 雷鸟(Thunderbird)收取Gmail出错,收到警告邮件

    如题,每次打开thunderbird都会收到以下提醒邮件,后来发现,只要将thunderbird中和google服务有关的插件卸载掉就可以了 We prevented the sign-in atte ...

  4. 如何在 Debian / Ubuntu 服务器上架设 L2TP / IPSec VPN

    本站的 Rio 最近在一台 Ubuntu 和一台 Debian 主机上配置了 L2TP / IPSec VPN,并在自己的博客上做了记录.原文以英文写就,我把它大致翻译了一下,结合我和 Rio 在设置 ...

  5. pom.xml中<dependency>

    当想下载jar包时,需要在pom.xml追加<dependency>即可. 通过如下餐叙: 如下图 http://mvnrepository.com/artifact/cglib/cgli ...

  6. C#程序中获取电脑硬件配置信息的一种方法

    本文介绍获取cpu信息和内存信息的方法,根据本文所举例的代码可以举一反三获取更多信息. 获取cpu名称的方法: public string GetCpuInfo() { ManagementObjec ...

  7. pl/sql编程

    body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI ...

  8. gif图简介

    多媒体教程 - GIF 图 GIF 是在 Web 上使用的主要图像格式之一. 本文详细讲解了 GIF 图像的特性和使用技巧. 理解图像格式 无论是 HTML 还是 XHTML 都没有规定图像的官方格式 ...

  9. java_设计模式_组合模式_Composite Pattern(2016-08-12)

    概念: 组合模式(Composite Pattern)将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性. 有时候又叫做部分-整体模式,它使我们树 ...

  10. 18款js和jquery文字特效代码分享

    18款js和jquery文字特效代码分享 jQCloud标签云插件_热门城市文字标签云代码 js 3d标签云特效关键词文字球状标签云代码 原生JS鼠标悬停文字球状放大显示效果代码 原生js文字动画圆形 ...