Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a fragment not attatched to an activity but only a context?

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?

like image 969
Nemo Avatar asked Dec 29 '19 07:12

Nemo


People also ask

Which method is called when a fragment is not connected to the activity?

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 .

What is called when the fragment is detached from the activity?

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.

Can a fragment exist without an activity?

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.

Does fragment have context?

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.


1 Answers

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).

like image 99
ianhanniballake Avatar answered Oct 04 '22 21:10

ianhanniballake