fragment without activity
I have been asked an interview question that Can a fragment exist without activity ? I searched for the answers but didn’t get the proper answer and explanation, can someone help me in this question ? Answers will be appreciated.
6 Solutions collect form web for “fragment without activity”
Yes, you can do this anywhere:
As fragments must have a parameter-less constructor.
However its lifecycle doesn’t kick in until it is attached. So
onCreateView, etc. are only called when it is attached. So most fragments do nothing until they are attached.
It can exist as an object in memory (by creating it with
new), but it needs to be attached to an Activity in order to appear on the screen, assuming it has any UI (fragments don’t have to have UI).
An Fragment can exist independently but in order to Display it you need the help of an Activity. The Activity will act like a container for the Fragment(s).
fragment is not required to be a part of the
Activity layout; you may also use a
fragment without its own
UI as an invisible worker for the
Activity but it needs to be attached to an
Activity in order to appear on the screen.
Android app must have a Activity or FragmentActivity that handles the fragment…
Fragment cant’s be initiated without Activity or FragmentActivity..
As soon as you create a Fragement class,it exists but in order to appear on the UI you must attach that fragment to a activity because a fragment’s lifecycle runs parallel to Activity’s LifeCycle.So, without any call to Activity onCreate() there will be no call for onAttach(),onCreate(),onCreateView() and onActivitycreated() of fragment and so it can’t be started.