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
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.
Android app must have an Activity or FragmentActivity that handles the fragment.
Fragment can't be initiated without Activity or FragmentActivity.
A 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).
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);
}
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.
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.