Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment without activity

Tags:

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?

like image 562
Shubham Avatar asked May 19 '14 06:05

Shubham


People also ask

Can a fragment exist without activity?

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.

Can we call fragment without activity in Android?

Android app must have an Activity or FragmentActivity that handles the fragment. Fragment can't be initiated without Activity or FragmentActivity.

Can we have fragment without UI?

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.

What happens to fragment when activity is stopped?

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.


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

like image 188
weston Avatar answered Sep 19 '22 06:09

weston