如何在一个activity中添加一个fragment

2025-04-14 13:02:45
推荐回答(1个)
回答1:

你能够像一个视图那样给Fragment指定布局属性。下例说明了给Activity指定两个Fragment的布局文件。


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属性指定了在布局中要实例化的Fragment。

当系统创建这个Activity布局时,它实例化在布局中指定的每一个Fragment,并且分别调用onCreateView(),来获取每个Fragment的布局。然后系统会在Activity布局中插入通过元素中声明直接返回的视图。

注:每个Fragment需要一个唯一的标识,这样能够在Activity被重启时系统使用这个ID来恢复Fragment(并且你能够使用这个ID获取执行事务的Fragment,如删除)。有三种给Fragment提供ID的方法:

A. 使用android:id属性来设置唯一ID;

B. 使用android:tag属性来设置唯一的字符串;

C. 如果没有设置前面两个属性,系统会使用容器视图的ID。