一、碎片(Fragment)的创建和使用
碎片是可以嵌入在活动中的UI片段。
静态加载碎片
创建碎片的布局文件(left_fragment.xml),布局文件中可以添加其他控件,如按钮、文本框等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:text="Button" />
</LinearLayout>
创建用来加载该碎片布局文件的类(LeftFragment.java)
1
2
3
4
5
6
7
8public class LeftFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
}
}在活动相关的布局xml文件中添加该碎片
1
2
3
4
5
6
7
8
9
10
11
12
13<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.chapter4_fragmenttest.LeftFragment"
android:id="@+id/left_fragment" />
</LinearLayout>其中android:name用来显式指明要添加的碎片类名
动态加载碎片
1 | FragmentManager fragmentManager = getSupportFragmentManager(); |
动态加载为五步:
- 创建待添加的碎片实例;
- 获取FragmentManager,在活动中可以直接通过调用getSupportFragmentManager()方法得到;
- beginTransaction()开启一个事务
- 向容器内添加或替换碎片,一般用replace()方法
- 提交事务,调用commit()方法来完成
【addToBackStck()用于将事务添加到返回栈中】
二、碎片状态
运行状态:当一个碎片可见,并且它所关联的活动正处于运行状态。
暂停状态:当一个活动进入暂停状态(另一个未占满屏幕的活动被添加到了栈顶),与该活动相关联的可见碎片就会进入暂停状态。
停止状态:当一个活动进入停止状态,与其相关联的碎片就进入停止状态;或通过调用FragmentTransaction的remove、replace方法将碎片从活动中移除,但在事务提交之前调用addToBackStack()方法。
销毁状态:碎片总是依附于活动而存在,因此当活动被销毁时,与它相关联的碎片就进入到销毁状态;或者通过调用FragmentTransaction的remove、replace方法将碎片从活动中移除,但在事务提交之前并没有调用addToBackStack()方法。
三、碎片回调
onAttach():将碎片和活动建立关联的时候调用;
onCreateView():为碎片创建视图(加载布局)时调用;
onActivityCreated():确保与碎片相关联的活动一定已经创建完毕时调用;
onDestroyView():与碎片关联的视图被移除时调用;
onDetach():碎片和活动解除关联时调用。