I have been asked an interview question: Can a fragment exist without activity? I searched for answers but didn't get a proper answer and explanation. Can someone help?
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.
Android app must have an Activity or FragmentActivity that handles the fragment. Fragment can't be initiated without Activity or FragmentActivity.
We use a fragment without a UI to act as a 'controller' picking up messages (broadcasts) from other fragments and modifying child controls. It provides a nice level of separation without polluting the parent activity code ensuring portability and modularisation... one of the big wins when using Fragment s.
A paused Fragment is still alive (all state and member information is retained by the system), but it will be destroyed if the Activity is destroyed. If the user presses the Back button and the Fragment is returned from the back stack, the lifecycle resumes with the onCreateView() callback.
Yes, you can do this anywhere:
new YourFragment();
As fragments must have a parameter-less constructor.
However its lifecycle doesn't kick in until it is attached. So onAttach
, onCreate
, onCreateView
, etc. are only called when it is attached. So most fragments do nothing until they are attached.
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