When is a fragment not attatched to an activity but only a context?
Fragments are not required to be associated with a FragmentActivity
. Instead, they are actually associated with a FragmentController
, which FragmentActivity
happens to create and manage on your behalf, calling the appropriate dispatch methods as necessary as the hosting activity is created, started, etc.
This level of indirection is how Facebook's Chat Heads (which displayed a Window
managed by a Service
) is able to reuse the same Fragment
instances that a FragmentActivity
uses and how building Navigation apps for Android Automotive (which use a CarAppService
to display the Automotive app) allows you to also reuse Fragments.
Of course, if your Fragment is always created from within one of your Activities, then, yes, you can absolutely assume that requireActivity()
will return a FragmentActivity
anytime isAdded()
returns true
- i.e., between onAttach()
and onDetach()
. That does indeed include in lifecycle methods such as onViewCreated()
or anything associated with your Fragment's views (such as an OnClickListener
).