生命周期函数
Fragment的生命周期依赖于其所属Activity的生命周期,只有当Activity处于Resumed状态时,Fragment的生命周期才是独立的,另外Fragment的视图在将其添加到Activity后,会作为Activity的布局的一部分。
onAttach called once the fragment is associated with its activity。Fragment被添加到Activity时调用
onCreate called to do initial creation of the fragment。
onCreateVIew creates and returns the view hierarchy associated with the fragment。根据布局文件创建视图,返回的视图被添加到Activity的布局中
onActivityCreated tells the fragment that its activity has completed its own Activity.onCreate().
onViewStateRestored tells the fragment that all of the saved state of its view hierarchy has been restored
onStart makes the fragment visible to the user (based on its containing activity being started)
onResume makes the fragment begin interacting with the user (based on its containing activity being resumed)
onPause fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
onStop fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
onDestroyView allows the fragment to clean up resources associated with its View。Fragment的contentView从Activity移除时调用
onDestroy called to do final cleanup of the fragment's state。也就是清除该Fragment的相关状态
onDetach called immediately prior to the fragment no longer being associated with its activity.
与Activity的通信方式
1 接口实现,这是Android官方推荐的方式,比较常见的实现方式
a 在Fragment类中定义一个接口,并在Fragment中持有该接口类型的引用
b 在Activity中实现这个接口,相关方法的参数可以理解为Fragment传给Activity的信息,而返回值就是Activity给Fragment的回信
c 在Activity中创建Fragment的实例时,通过setListner或者其他的方式将Activity作为接口的实例传递给Fragment的引用
d 在Fragment中通过接口的引用调用接口的相关方法实现通信
2 Handler机制
3 Eventbus
4 直接在Activity定义public方法,在Fragment中调用,这样的弊端是Activity与Fragment的耦合度很高
关于FragmentTransaction
通过FragmentTransaction可以执行添加,移除和替换Fragment的操作,最后通过commit()提交操作,在此之前,可以通过addToBackStack方法,将此次操作的FragmentTransaction添加到FragmentManager的返回栈(其实现是一个ArrayList<Fragment>)中,这样做的用途是,用户可以通过返回键回到之前的Fragment,而不是直接返回上一个Activity。addToBackStack方法带来的另一个影响是,如果没有在执行FragmentTransaction.remove()前调用addToBackStack(),则transaction提交时该Fragment会被销毁,用户将无法回退到该Fragment。 不过,如果您在删除Fragment前调用了addToBackStack(),则系统会停止该Fragment,并在用户回退时将其恢复。
如果向FragmentTransaction添加了多个更改(如又一个add()或remove()),并且调用了addToBackStack(),则在调用commit()前应用的所有更改都将作为单一FragmentTransaction添加到返回栈,并且返回按钮会将它们一并撤消。
另外调用commit()方法,不一定会立即执行当前的FragmentTransaction,想要立即执行,需要调用executePendingTransactions方法。只能在 Activity保存其状态(用户离开 Activity)之前使用commit()提交事务。如果您试图在该时间点后提交,则会引发异常。 这是因为如需恢复 Activity,则提交后的状态可能会丢失。 对于丢失提交无关紧要的情况,请使用commitAllowingStateLoss()。