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?
-
4read the docs http://developer.android.com/guide/components/fragments.html. – Raghunandan May 19 '14 at 06:50
-
Quoting docs "A 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". Only in this case you can have fragment not attached to activity – Raghunandan May 19 '14 at 06:55
7 Answers
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.

- 32,989
- 7
- 91
- 109

- 54,145
- 21
- 145
- 203
-
2Somebody asked me if a service can have Fragment. I said yes, he was surprised. But one should remember that one can have Fragment and call any of its method but as mentioned by @weston its life-cycle will not kick in until attached to Activity. Also, one need instance of FragmentManager to do manage them (which is possible only in Activity). – Tabrej Khan Nov 06 '14 at 06:57
-
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).

- 38,365
- 12
- 84
- 104
A 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.

- 5,687
- 3
- 26
- 42
As soon as you create an instance of the Fragment class, it exists, but in order for it to appear on the UI, you must attach that fragment to an activity because a fragment's lifecycle runs parallel to an activity's lifecycle. Without any call to Activity's onCreate(), there will be no call for onAttach(), onCreate(), onCreateView() and onActivityCreated() of fragment and so it can't be started.

- 9,564
- 146
- 81
- 122

- 7,333
- 7
- 50
- 71
Android app must have an Activity or FragmentActivity that handles the fragment.
Fragment can't be initiated without Activity or FragmentActivity.

- 9,564
- 146
- 81
- 122

- 3,585
- 3
- 17
- 18
I read above top rated answer , i am not disagreeing but android already provides to make independent fragment without activity DialogFragment , which extends fragment . if you want show in full screen first extends DialogFragment then
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}

- 8,647
- 2
- 19
- 17