derekargueta/Android-Interview-Questions

Fragment vs activity

IlyaEremin opened this issue · 4 comments

There is question:
•What is the difference between a fragment and an activity? Explain the relationship between the two.

Can someone answer first question?
I know that many fragments can be placed in one activity and that fragment cannot exists without activity (in really useful way).

In fact, I recommended to image it to be a sticky, contents are on it, you could put it wherever you want, and easily replace it with another one, and they could be reused, however you do need a surface(Activity) to put it on, that part would be onAttach(), check fragment life cycle to get more details. This is just my way to make it easier to understand that why we need it

Yeeeap.
But what is the difference between a fragment and an activity?
How can we compare these two things?

Both a Fragment and an Activity are a form of a UI container, meaning both can group together UI components. However, a screen can (and must) have one Activity acting as the base container. If you need to group together subcomponents, either for reusability or organization, you can place them in a Fragment, and then place that Fragment into the Activity. An Activity can contain multiple Fragments, and Fragments can contain multiple Fragments, but nothing can contain an Activity since it is the base component.

It's like how on a website, you have one <html> tag to group the whole site together, but to group smaller components you use a <div> tag. Or if anyone is familiar with iOS development, it's like comparing a UIViewController, which controls the whole screen, to a UIView which is only a sub-container that is placed on the UIViewController.

According to Google it's recommended to use Fragments whenever possible to swap out UI components rather than create and navigate to the entirely new Activity, but there are cases where you need to or should swap the entire screen which is where Activities come in.

A quote from the Android documentation on Fragments: "You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities)."

I didn't put a link in the README because I haven't found a website that explains the differences well enough :/ Hopefully answers your question @IlyaEremin!

@derekargueta thank you very much! Super answer