首页 > 代码库 > Fragment的学习使用
Fragment的学习使用
1.对于Fragment学习,先看官方的一段说明:
A Fragment is a piece of an application‘s user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager,
which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager(). The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within
a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle
is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed. All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular
during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will
occur in some cases during state restore.
fragment可以看做是置于Activity之中的一部分应用程序的用户界面或用户行为。你可以通过FragmentManager 与 Fragment进行交互,而FragmentManager 可以通过Activity.getFragmentManager()得到,也可以通过Fragment.getFragmentManager()得到。
Fragment可以通过众多的方式达到一系列你想要的结果,其核心是展示运行在大Activity下的独特行为或界面。 Fragment与它所在的Activity紧密相连,不能脱离Activity独立存在,尽管
Fragment定义了自己的生命周期,但是它却依赖于它所在的Activity生命周期。比如,如果Activity停止了,其内部的fragment就不会有正在运行的了;Activity销毁的话,其内部的fragment也
会全部被销毁。
所有Fragment的子类都必须含有一个公有的不带参数的构造器,如果有必要的话,系统框架framework会经常重新实例化这个fragment类,尤其是在生命周期的restore状态下,他正是通过这个无参构造器实现的,如果子类中没有无参构造器,可能会在restore状态下抛出 runtime exception
2.那么首先了解一下生命周期
生命周期可以参考官方文档: https://developer.android.google.cn/reference/android/app/Fragment.html#Lifecycle
Fragment的学习使用