At the docs for Fragment.getActivity() it says: Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.
But how can a fragment not be associated with an activity? I mean, don't I always need an activity to show anything in Android?
The onActivityCreated() method is called after onCreateView() and before onViewStateRestored() . onDestroyView() : Called when the View previously created by onCreateView() has been detached from the Fragment . This call can occur if the host Activity has stopped, or the Activity has removed the Fragment .
The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached from its host activity. The fragment is no longer active and can no longer be retrieved using findFragmentById() . onDetach() is always called after any Lifecycle state changes.
Fragments cannot live on their own--they must be hosted by an activity or another fragment. The fragment's view hierarchy becomes part of, or attaches to, the host's view hierarchy.
The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment. Then: you can dereference the fragment to get activity, context or applicationcontext as you desire: this.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With