`
qilixiang012
  • 浏览: 202653 次
文章分类
社区版块
存档分类
最新评论

android fragment详解

 
阅读更多

Fragment概述及其设计哲学


实际上就是为了适应不同的屏幕分辨率,有的屏幕在一个Activity中可以包含一个Fragment,有的则可以包含多个,所以需要根据不同的配置调整显示方式,例如在同一个Activity里面显示两个Fragment,或者在一个Activity里面显示其中一个Fragment,另外一个Activity里面显示另外一个Fragment,实际上就是把显示内容划分成多块,每一块都有各自的生命周期,但是每一块又是跟它所在的Activity分不开的,Fragment的生命周期依赖Activity的生命周期而存在。你可以将fragment包含到多个activity中. 这点特别重要, 因为这允许你将你的用户体验适配到不同的屏幕尺寸.举个例子,你可能会仅当在屏幕尺寸足够大时,在一个activity中包含多个fragment,并且,当不属于这种情况时,会启动另一个单独的,使用不同fragment的activity.


使用支持库

如果您的应用需要运行在3.0及以上的版本,可以忽略这部分内容。
如果您的应用使用在3.0以下、1.6及以上的版本,需要使用支持库来构建。
使用支持库的步骤:
1.使用SDK下的SDK Manager工具下载Android Support Package


2. 在您的Android工程的顶级目录下创建一个libs目录
3. 找到您的SDK下的/extras/android/support/v4/android-support-v4.jar,并且拷贝到您的项目的libs下,选中这个jar包 → 右键 → Build Path → Add to Build Path
4.在您的项目的Manifest.xml文件的<manifest>标签下添加:
<uses-sdkandroid:minSdkVersion="4"
  android:targetSdkVersion="8"/>
  其中targetSdkVersion是您的软件最小支持的版本
5.如果您的项目支持3.0以下的版本,请导入如下的包:android.support.v4.*;
在使用Fragment的Activity请继承FragmentActivity而不是Activity。如果您的系统是3.0或以上版本,同样需要导入类似的包,但是可以使用普通的Activity。


创建Fragment

要创建一个fragment, 必须创建一个 Fragment 的子类 (或者继承自一个已存在的它的子类). Fragment类的代码看起来很像 Activity 。它包含了和activity类似的回调方法, 例如onCreate()、 onStart()、onPause()以及 onStop()。事实上, 如果你准备将一个现成的Android应用转换到使用fragment,可能只需简单的将代码从你的activity的回调方法分别移动到你的fragment的回调方法即可。

通常, 应当至少实现如下的生命周期方法:
onCreate()
当创建fragment时, 系统调用该方法.
在实现代码中,应当初始化想要在fragment中保持的必要组件, 当fragment被暂停或者停止后可以恢复.
onCreateView()
fragment第一次绘制它的用户界面的时候, 系统会调用此方法. 为了绘制fragment的UI,此方法必须返回一个View, 这个view是你的fragment布局的根view. 如果fragment不提供UI, 可以返回null.
onPause()
用户将要离开fragment时,系统调用这个方法作为第一个指示(然而它不总是意味着fragment将被销毁.) 在当前用户会话结束之前,通常应当在这里提交任何应该持久化的变化(因为用户有可能不会返回).

大多数应用应当为每一个fragment实现至少这3个方法,但是还有一些其他回调方法你也应当用来去处理fragment生命周期的各种阶段.全部的生命周期回调方法将会在后面章节 Handlingthe Fragment Lifecycle 中讨论.

除了继承基类 Fragment , 还有一些子类你可能会继承:
DialogFragment

显示一个浮动的对话框.
用这个类来创建一个对话框,是使用在Activity类的对话框工具方法之外的一个好的选择,
因为你可以将一个fragment对话框合并到activity管理的fragment back stack中,允许用户返回到一个之前曾被摒弃的fragment.
ListFragment
显示一个由一个adapter(例如 SimpleCursorAdapter)管理的项目的列表, 类似于ListActivity.
它提供一些方法来管理一个list view, 例如 onListItemClick()回调来处理点击事件.
PreferenceFragment
显示一个 Preference对象的层次结构的列表, 类似于PreferenceActivity.
这在为你的应用创建一个"设置"activity时有用处.


创建Fragment的两种方式

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

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

<span style="font-family:SimSun;font-size:18px;"><?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></span>
其中android:name属性填上你自己创建的fragment的完整类名。
  当系统创建这个Activity的布局文件时,系统会实例化每一个fragment,并且调用它们的onCreateView()方法,来获得相应fragment的布局,并将返回值插入fragment标签所在的地方。
  有三种方法为Fragment提供ID:
  android:id属性:唯一的id
  android:tag属性:唯一的字符串
  如果上面两个都没提供,系统使用容器view的ID。

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

当activity运行的任何时候, 都可以将fragment添加到activity layout.只需简单的指定一个需要放置fragment的ViewGroup.为了在你的 activity中操作fragment事务(例如添加,移除,或代替一个fragment),必须使用来自FragmentTransaction 的API.

  首先,需要一个FragmentTransaction实例: 

<span style="font-family:SimSun;font-size:18px;">FragmentManager fragmentManager = getFragmentManager()

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();</span>
(注,如果import android.support.v4.app.FragmentManager;那么使用的是:FragmentManager fragmentManager = getSupportFragmentManager();)

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

<span style="font-family:SimSun;font-size:18px;">ExampleFragment fragment = new ExampleFragment();

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

fragmentTransaction.commit();</span>

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

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

实例
  练习的例子:

  写一个类继承自Fragment类,并且写好其布局文件(本例中是两个TextView),在Fragment类的onCreateView()方法中加入该布局。
  之后用两种方法在Activity中加入这个fragment:
  第一种是在Activity的布局文件中加入<fragment>标签;
  第二种是在Activity的代码中使用FragmentTransaction的add()方法加入fragment。
贴出代码:
  自己定义的fragment类: 

<span style="font-family:SimSun;font-size:18px;">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");
    }
    
    

}</span>

传入onCreateView()的container参数是你的fragmentlayout将被插入的父ViewGroup(来自activity的layout) savedInstanceState 参数是一个Bundle, 如果fragment是被恢复的,它提供关于fragment的之前的实例的数据,
inflate() 方法有3个参数:
想要加载的layout的resource ID.
加载的layout的父ViewGroup.
传入container是很重要的, 目的是为了让系统接受所要加载的layout的根view的layout参数,
由它将挂靠的父view指定.
布尔值指示在加载期间, 展开的layout是否应当附着到ViewGroup (第二个参数).
(在这个例子中, 指定了false, 因为系统已经把展开的layout插入到container –传入true会在最后的layout中创建一个多余的view group.)

fragment的布局文件:

<span style="font-family:SimSun;font-size:18px;">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></span>
主Activity:

<span style="font-family:SimSun;font-size:18px;">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();
    }

}</span>

add()的第一个参数是fragment要放入的ViewGroup, 由resource ID指定,第二个参数是需要添加的fragment.一旦用FragmentTransaction做了改变,为了使改变生效,必须调用commit().

Activity的布局文件:

<span style="font-family:SimSun;font-size:18px;">activity_learn_fragment.xml

<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></span>


Fragment管理与Fragment事务

添加一个无UI的fragment

之前的例子展示了对UI的支持, 如何将一个fragment添加到activity.然而,也可以使用fragment来为activity提供后台行为而不用展现额外的UI.
要添加一个无UI的fragment, 需要从activity使用 add(Fragment, String)来添加fragment (为fragment提供一个唯一的字符串"tag", 而不是一个view ID).这么做添加了fragment,但因为它没有关联到一个activity layout中的一个view, 所以不会接收到onCreateView()调用.因此不必实现此方法.
为fragment提供一个字符串tag并不是专门针对无UI的fragment的–也可以提供字符串tag给有UI的fragment–但是如果fragment没有UI,那么这个tag是仅有的标识它的途径.如果随后你想从activity获取这个fragment, 需要使用 findFragmentByTag().

管理Fragment

要在activity中管理fragment,需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例.
可以通过FragmentManager做一些事情, 包括:
使用findFragmentById()(用于在activity layout中提供一个UI的fragment)或findFragmentByTag()(适用于有或没有UI的fragment)获取activity中存在的fragment
将fragment从后台堆栈中弹出, 使用 popBackStack() (模拟用户按下BACK 命令).
使用addOnBackStackChangeListener()注册一个监听后台堆栈变化的listener,用于监听后台栈的变化

获得FragmentTransaction对象,动态增加,删除,替换Fragment

处理Fragment事务

关于在activity中使用fragment的很强的一个特性是:根据用户的交互情况,对fragment进行添加,移除,替换,以及执行其他动作.提交给activity的每一套变化被称为一个事务,可以使用在FragmentTransaction中的 API 处理.我们也可以保存每一个事务到一个activity管理的backstack,允许用户经由fragment的变化往回导航(类似于通过 activity往后导航).

从 FragmentManager 获得一个FragmentTransaction实例 :

<span style="font-family:SimSun;font-size:18px;">FragmentManager fragmentManager =getFragmentManager();  
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();</span>
每一个事务都是同时要执行的一套变化.可以在一个给定的事务中设置你想执行的所有变化,使用诸如 add()、remove()和 replace().然后, 要给activity应用事务, 必须调用commit().

  在调用commit()之前, 你可能想调用 addToBackStack(),将事务添加到一个fragment事务的backstack. 这个back stack由activity管理, 并允许用户通过按下 BACK按键返回到前一个fragment状态.

举个例子, 这里是如何将一个fragment替换为另一个, 并在后台堆栈中保留之前的状态:

<span style="font-family:SimSun;font-size:18px;">// Create new fragment and transaction  
Fragment newFragment = newExampleFragment();  
FragmentTransaction transaction =getFragmentManager().beginTransaction();  
// Replace whatever is in thefragment_container view with this fragment,  
// and add the transaction to the backstack  
transaction.replace(R.id.fragment_container,newFragment);  
transaction.addToBackStack(null);  
// Commit the transaction  
transaction.commit();  </span>
在这个例子中,newFragment替换了当前layout容器中的由R.id.fragment_container标识的fragment.通过调用 addToBackStack(), replace事务被保存到back stack,因此用户可以回退事务,并通过按下BACK按键带回前一个fragment.
如果添加多个变化到事务(例如add()或remove())并调用addToBackStack(),然后在你调用commit()之前的所有应用的变化会被作为一个单个事务添加到后台堆栈, BACK按键会将它们一起回退.
添加变化到 FragmentTransaction的顺序不重要, 除以下例外:

必须最后调用 commit().
如果添加多个fragment到同一个容器, 那么添加的顺序决定了它们在view hierarchy中显示的顺序.
当执行一个移除fragment的事务时, 如果没有调用 addToBackStack(), 那么当事务提交后,那个fragment会被销毁,并且用户不能导航回到它. 有鉴于此, 当移除一个fragment时,如果调用了addToBackStack(), 那么fragment会被停止, 如果用户导航回来,它将会被恢复.
提示: 对于每一个fragment事务, 你可以应用一个事务动画,通过在提交事务之前调用setTransition()实现.

调用 commit() 并不立即执行事务.恰恰相反, 它将事务安排排期, 一旦准备好,就在activity的UI线程上运行(主线程).如果有必要, 无论如何, 你可以从你的UI线程调用executePendingTransactions()来立即执行由commit()提交的事务. 但这么做通常不必要,除非事务是其他线程中的任务的一个从属.

警告:你只能在activity保存它的状态(当用户离开activity)之前使用commit()提交事务.

Fragment与Activity的通信

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.(两个Fragment之间的通信通过Fragment完成,绝不应该在Fragment之间直接进行通信)

尽管Fragment被实现为一个独立于Activity的对象,并且可以在多个activity中使用,但一个给定的fragment实例是直接绑定到包含它的activity的. 特别的,fragment可以使用 getActivity() 访问Activity实例, 并且容易地执行比如在activitylayout中查找一个view的任务.

View listView =getActivity().findViewById(R.id.list);

同样地,activity可以通过从FragmentManager获得一个到Fragment的引用来调用fragment中的方法, 使用

findFragmentById() 或 findFragmentByTag().(The host activity can deliver messages to a fragment by capturing theFragmentinstance withfindFragmentById(), then directly call the fragment's public methods.

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

官方例子:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article

        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
        
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
}

Fragment与Activity之间传递数据

Activity向Fragment传递数据:在Activity中创建Bundle数据包,并调用Fragment的setArgument(Bundle bundle)方法即可将Bundle传给Fragment

SelectBookActivity:

	@Override
	public void onItemSelected(Integer id)
	{
		// 创建Bundle,准备向Fragment传入参数
		Bundle arguments = new Bundle();
		arguments.putInt(BookDetailFragment.ITEM_ID, id);
		// 创建BookDetailFragment对象
		BookDetailFragment fragment = new BookDetailFragment();
		// 向Fragment传入参数
		fragment.setArguments(arguments);
		// 使用fragment替换book_detail_container容器当前显示的Fragment
		getFragmentManager().beginTransaction()
			.replace(R.id.book_detail_container, fragment)
			.commit();  //①
	}
}
Fragment:

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 如果启动该Fragment时包含了ITEM_ID参数
		if (getArguments().containsKey(ITEM_ID))
		{
			book = BookContent.ITEM_MAP.get(getArguments()
				.getInt(ITEM_ID)); //①
		}
	}

Fragment向Activity传递数据或Activity需要在Fragment运行中进行实时通信:在Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回调接口,这样Fragment即可调用该回调方法将数据传给Activity

为Activity创建事件回调方法

在一些情况下, 你可能需要一个fragment与activity分享事件. 一个好的方法是在fragment中定义一个回调的interface,并要求宿主activity实现它.当activity通过interface接收到一个回调, 必要时它可以和在layout中的其他fragment分享信息.

例如, 如果一个新的应用在activity中有2个fragment – 一个用来显示文章列表(framgent A), 另一个显示文章内容

(fragment B) – 然后 framgent A必须告诉activity何时一个list item被选中,然后它可以告诉fragmentB去显示文章.

在这个例子中, OnArticleSelectedListener 接口在fragment A中声明:

<span style="font-family:SimSun;font-size:18px;">public static class FragmentA extends ListFragment {  
    ...  
    // Container Activity must implement this interface  
    public interface OnArticleSelectedListener {  
        public void onArticleSelected(Uri articleUri);  
   
    }  
    ...  
} </span>
然后fragment的宿主activity实现 OnArticleSelectedListener 接口, 并覆写 onArticleSelected() 来通知fragment B,从fragment A到来的事件.为了确保宿主activity实现这个接口, fragment A的 onAttach() 回调方法(当添加fragment到activity时由系统调用) 通过将作为参数传入onAttach()的Activity做类型转换来实例化一个OnArticleSelectedListener实例.
<span style="font-family:SimSun;font-size:18px;">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 implementOnArticleSelectedListener");  
        }  
    }  
   
    ...  
   
}  </span>
如果activity没有实现接口, fragment会抛出 ClassCastException 异常. 正常情形下,mListener成员会保持一个到activity的OnArticleSelectedListener实现的引用, 因此fragment A可以通过调用在OnArticleSelectedListener接口中定义的方法分享事件给activity.例如, 如果fragment A是一个 ListFragment的子类, 每次用户点击一个列表项, 系统调用在fragment中的onListItemClick(),然后后者调用 onArticleSelected() 来分配事件给activity.
<span style="font-family:SimSun;font-size:18px;">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);  
    }  
   
    ...  
   
}  </span>
传给 onListItemClick() 的 id 参数是被点击的项的行ID, activity(或其他fragment)用来从应用的 ContentProvider 获取文章.


添加项目到ActionBar

你的fragment可以通过实现 onCreateOptionMenu() 提供菜单项给activity的选项菜单(以此类推, Action Bar也一样).为了使这个方法接收调用,无论如何, 你必须在 onCreate() 期间调用 setHasOptionsMenu() 来指出fragment愿意添加item到选项菜单(否则, fragment将接收不到对 onCreateOptionsMenu()的调用).

随后从fragment添加到Option菜单的任何项,都会被追加到现有菜单项的后面.当一个菜单项被选择, fragment也会接收到对 onOptionsItemSelected() 的回调.也可以在你的fragment layout中通过调用registerForContextMenu() 注册一个view

来提供一个环境菜单.当用户打开环境菜单, fragment接收到一个对 onCreateContextMenu() 的调用.当用户选择一个项目, fragment接收到一个对onContextItemSelected() 的调用.

注意: 尽管你的fragment会接收到它所添加的每一个菜单项被选择后的回调, 但实际上当用户选择一个菜单项时, activity会首先接收到对应的回调.如果activity的on-item-selected回调函数实现并没有处理被选中的项目, 然后事件才会被传递到fragment的回调.

这个规则适用于选项菜单和环境菜单.


附上疯狂Android实例源码(整合了嵌入Fragment的两种方式,及Fragment与Activity之间相互通信的方法):

主Activity的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来显示图书标题 -->
<TextView
	style="?android:attr/textAppearanceLarge"
	android:id="@+id/book_title"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:padding="16dp"/>
<!-- 定义一个TextView来显示图书描述 -->
<TextView
	style="?android:attr/textAppearanceMedium"
	android:id="@+id/book_desc"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:padding="16dp"/>
</LinearLayout>
主Activity:
package org.crazyit.app;

import android.app.Activity;
import android.os.Bundle;

public class SelectBookActivity extends Activity implements
		BookListFragment.Callbacks
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 加载/res/layout目录下的activity_book_twopane.xml布局文件
		setContentView(R.layout.activity_book_twopane);
	}
	// 实现Callbacks接口必须实现的方法
	@Override
	public void onItemSelected(Integer id)
	{
		// 创建Bundle,准备向Fragment传入参数
		Bundle arguments = new Bundle();
		arguments.putInt(BookDetailFragment.ITEM_ID, id);
		// 创建BookDetailFragment对象
		BookDetailFragment fragment = new BookDetailFragment();
		// 向Fragment传入参数
		fragment.setArguments(arguments);
		// 使用fragment替换book_detail_container容器当前显示的Fragment
		getFragmentManager().beginTransaction()
			.replace(R.id.book_detail_container, fragment)
			.commit();  //①
	}
}
用xml元素嵌入的Fragment(是一个ListFragment组件):

package org.crazyit.app;

import org.crazyit.app.model.BookContent;

import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class BookListFragment extends ListFragment
{
	private Callbacks mCallbacks;
	// 定义一个回调接口,该Fragment所在Activity需要实现该接口
	// 该Fragment将通过该接口与它所在的Activity交互
	public interface Callbacks
	{
		public void onItemSelected(Integer id);
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 为该ListFragment设置Adapter
		setListAdapter(new ArrayAdapter<BookContent.Book>(getActivity(),
				android.R.layout.simple_list_item_activated_1,
				android.R.id.text1, BookContent.ITEMS));
	}
	// 当该Fragment被添加、显示到Activity时,回调该方法
	@Override
	public void onAttach(Activity activity)
	{
		super.onAttach(activity);
		// 如果Activity没有实现Callbacks接口,抛出异常
		if (!(activity instanceof Callbacks))
		{
			throw new IllegalStateException(
				"BookListFragment所在的Activity必须实现Callbacks接口!");
		}
		// 把该Activity当成Callbacks对象
		mCallbacks = (Callbacks)activity;
	}
	// 当该Fragment从它所属的Activity中被删除时回调该方法
	@Override
	public void onDetach()
	{
		super.onDetach();
		// 将mCallbacks赋为null。
		mCallbacks = null;
	}
	// 当用户点击某列表项时激发该回调方法
	@Override
	public void onListItemClick(ListView listView
		, View view, int position, long id)
	{
		super.onListItemClick(listView, view, position, id);
		// 激发mCallbacks的onItemSelected方法
		mCallbacks.onItemSelected(BookContent
			.ITEMS.get(position).id);
	}

	public void setActivateOnItemClick(boolean activateOnItemClick)
	{
		getListView().setChoiceMode(
				activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
						: ListView.CHOICE_MODE_NONE);
	}
}
用动态事务加入的Fragment:

package org.crazyit.app;

import org.crazyit.app.model.BookContent;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BookDetailFragment extends Fragment
{
	public static final String ITEM_ID = "item_id";
	// 保存该Fragment显示的Book对象
	BookContent.Book book;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 如果启动该Fragment时包含了ITEM_ID参数
		if (getArguments().containsKey(ITEM_ID))
		{
			book = BookContent.ITEM_MAP.get(getArguments()
				.getInt(ITEM_ID)); //①
		}
	}

	// 重写该方法,该方法返回的View将作为Fragment显示的组件
	@Override
	public View onCreateView(LayoutInflater inflater
		, ViewGroup container, Bundle savedInstanceState)
	{
		// 加载/res/layout/目录下的fragment_book_detail.xml布局文件
		View rootView = inflater.inflate(R.layout.fragment_book_detail,
				container, false);
		if (book != null)
		{
			// 让book_title文本框显示book对象的title属性
			((TextView) rootView.findViewById(R.id.book_title))
					.setText(book.title);
			// 让book_desc文本框显示book对象的desc属性
			((TextView) rootView.findViewById(R.id.book_desc))
				.setText(book.desc);	
		}
		return rootView;
	}
}
动态事务加入Fragment的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来显示图书标题 -->
<TextView
	style="?android:attr/textAppearanceLarge"
	android:id="@+id/book_title"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:padding="16dp"/>
<!-- 定义一个TextView来显示图书描述 -->
<TextView
	style="?android:attr/textAppearanceMedium"
	android:id="@+id/book_desc"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:padding="16dp"/>
</LinearLayout>
模型类:

package org.crazyit.app.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookContent
{
	// 定义一个内部类,作为系统的业务对象
	public static class Book
	{

		public Integer id;
		public String title;
		public String desc;

		public Book(Integer id, String title, String desc)
		{
			this.id = id;
			this.title = title;
			this.desc = desc;
		}

		@Override
		public String toString()
		{
			return title;
		}
	}
	// 使用List集合记录系统所包含的Book对象
	public static List<Book> ITEMS = new ArrayList<Book>();
	// 使用Map集合记录系统所包含的Book对象	
	public static Map<Integer, Book> ITEM_MAP 
		= new HashMap<Integer, Book>();

	static
	{
		// 使用静态初始化代码,将Book对象添加到List集合、Map集合中
		addItem(new Book(1, "疯狂Java讲义"
			, "一本全面、深入的Java学习图书,已被多家高校选做教材。"));
		addItem(new Book(2, "疯狂Android讲义"
			, "Android学习者的首选图书,常年占据京东、当当、 "
			+ "亚马逊3大网站Android销量排行榜的榜首"));
		addItem(new Book(3, "轻量级Java EE企业应用实战"
			, "全面介绍Java EE开发的Struts 2、Spring 3、Hibernate 4框架"));
	}

	private static void addItem(Book book)
	{
		ITEMS.add(book);
		ITEM_MAP.put(book.id, book);
	}
}
清单文件:
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="org.crazyit.app"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk
		android:minSdkVersion="11"
		android:targetSdkVersion="15" />
	<application
		android:icon="@drawable/ic_launcher"
		android:label="@string/app_name">
		<activity
			android:name=".SelectBookActivity"
			android:label="@string/title_book_list">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
</manifest>


参考文章:http://blog.csdn.net/lilu_leo/article/details/7671533

参考资源
  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

参考博客:

http://blog.csdn.net/guolin_blog/article/details/8881711

http://blog.csdn.net/guolin_blog/article/details/8744943

http://blog.csdn.net/guolin_blog/article/details/13171191



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics