android fragment 教程,如何使用Android Fragment

fragment通常是宿主Activity UI的一部分,被作为activity整个view hierarchy的一部分被嵌入。添加fragmet到activity Layout有两种方法。如下所述。

一、在Activity的Layout文件中声明fragment

你可以像为View一样,为fragment指定layout属性(sdk3.0以后)。

例子是一个有2个fragment的activity:

XML/HTML代码<?xmlversion ="1.0"encoding="utf-8"?>

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/list"

android:layout_weight="1"

android:layout_width="0dp"

android:layout_height="match_parent"/>

android:id="@+id/viewer"

android:layout_weight="2"

android:layout_width="0dp"

android:layout_height="match_parent"/>

中的 android:name 属性指定了在layout中实例化的Fragment类。

当系统创建这个activity layout时,它实例化每一个在layout中指定的fragment,并调用每一个上的onCreateView()方法,来获取每一个fragment的layout。系统将从fragment返回的 View 直接插入到元素所在的地方。

注意:每一个fragment都需要一个唯一的标识,如果activity重启,系统可以用来恢复fragment(并且你也可以用来捕获fragment来处理事务,例如移除它)。

有3种方法来为一个fragment提供一个标识:

为 android:id 属性提供一个唯一ID;

为 android:tag 属性提供一个唯一字符串;

如果以上2个你都没有提供,系统使用容器view的ID。

二、使用FragmentManager将fragment添加到一个已存在的ViewGroup

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

可以按如下方法,从你的Activity取得一个FragmentTransaction 的实例:

Java代码FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然后你可以使用 add() 方法添加一个fragment,指定要添加的fragment和要插入的view。

Java代码ExampleFragment fragment =newExampleFragment();

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

fragmentTransaction.commit();

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

2012年12月18日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值