一、What is a fragment?
首先,fragment总是被嵌入到一个activity中,你可以把它看做是activity中的一个模块,也是用来呈现数据的,但它不需要在manifest中配置,因此可以看做一个轻量级的activity。它有着自己的生命周期,但又依赖与attach的activity。Fragment的出现是为了解决大屏适配的问题,但现在你可以利用fragment来实现更多的功能,比如微信的主界面、QQ的主界面(fragment+framelayout+其他)等。
二、How to create and use it ?
通常的步骤如下:
1.编写xml布局文件(类似activity对应的xml)
2.继承Fragment(或者DialogFragment、ListFragment),并在生命周期方法的onCreateView方法进行inflate
3.在activity的xml中使用,通过<fragment android:name="完整的包名">
4.在attach的activity中通过FragmentManager来findFragmentById或者findFragmentByTag(没有界面的fragment),然后通过FragmentTransaction来进行remove、replace、add等动态的操作,最后commit
三、Lifecycle
Fragment的生命周期往往依赖与attach的activity,比如activity如果resumed则fragment resumed,activity如果paused,则fragment paused,如果activity stopped 则 fragment stopped
如图所示
至少应该实现如下的几个回调方法: