简单探究Fragment
Fragment是什么
Fragment (碎片)是一种可以嵌入在活动中的UI片段它能让程序更加合理和充分的利用大屏幕的空间,因此平板上应用的非常广泛。Fragment和活动非常相似,同样包含布局,有自己的生命周期。你甚至可以将碎片理解成一个迷你型的活动。
Fragment生命周期
Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。官网这张图很好的说明了两者生命周期的关系:
可以看到Fragment比Activity多了几个额外的生命周期回调方法:
onAttach():当Fragment与Activity发生关联时调用。
onCreateView():创建该Fragment的视图
onActivityCreated():当Activity的onCreate方法返回时调用
onDestoryView():与onCreateView想对应,当该Fragment的视图被移除时调用
onDetach():与onAttach相对应,当Fragment与Activity关联被取消时调用
介绍完Fragment,现在我们来讲一讲它的应用
Fragment的应用
Fragment静态加载怎么用
这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中。
下面展示一个例子(我使用2个Fragment作为Activity的布局):
FirstFragment的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#999999"
tools:context=".test.FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="My Firat Fragment"
android:textSize="30dp"
android:gravity="center"/>
</FrameLayout>
SecondFragment的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#f9c3c3"
tools:context=".test.SecondFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="My Second Fragment"
android:textSize="30dp"
android:gravity="center" />
</FrameLayout>
两个fragment用不同颜色,便于区分
Activity的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".test.TestActivity">
<fragment