在Fragment.getActivity()的文档中,它说:Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.
但是片段如何不与活动关联?我的意思是,我不是总是需要活动才能在Android中显示任何内容吗?
片段不需要与关联FragmentActivity
。相反,它们实际上与关联FragmentController
,后者FragmentActivity
恰好代表您创建和管理,并在创建,启动托管活动时根据需要调用适当的调度方法。
这种间接级别是Facebook的聊天头(显示Window
为由管理Service
)如何重用与Fragment
实例相同的实例,FragmentActivity
以及如何为Android Automotive构建导航应用(使用CarAppService
以显示Automotive应用)来重用碎片。
当然,如果您总是从一个Activity中创建您的Fragment,那么可以,您可以绝对假定requireActivity()
它将FragmentActivity
随时isAdded()
返回true
-即介于onAttach()
和之间onDetach()
。实际上,这确实包含在生命周期中的方法,例如onViewCreated()
或与Fragment的视图相关联的任何方法(例如OnClickListener
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句