android – Fragment without activity-ThrowExceptions

Exception or error:

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?

How to solve:

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.


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


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


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.


Android app must have an Activity or FragmentActivity that handles the fragment.

Fragment can’t be initiated without Activity or FragmentActivity.


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

public void onCreate(Bundle savedInstanceState)




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.

Leave a Reply

Your email address will not be published. Required fields are marked *