ant2009
ant2009

Reputation: 22486

Should each Fragment have its own Activity?

Android Studio 0.8.10

I have developed an App that has 3 fragments. I have just used 1 Activity and when I want to display a different fragment I just replace the existing fragment with the one I want to display. However, as I have 3 fragments now, and maybe more in the future, I think this will get harder to manage.

I am just wondering what is the design pattern when programming with multiple fragments, should each fragment have its own activity?

I will be scaling this to Tablets in the future, so I am not sure what impact this will have if I stick with the multiple fragments and single activity.

Many thanks for any suggestions,

Upvotes: 0

Views: 330

Answers (2)

G. Blake Meike
G. Blake Meike

Reputation: 6715

Yeah, this can be really hard to figure out. I think a pretty good analogy, from the web application world, might be a servlet and a frame.

An Activity is like a servlet. It is one page in your app's workflow.

A Fragment, on the other hand, is like a block of content. It might appear in several different contexts and it might be served by several different servlets.

In MVC terms, the activity is largely part of the controller. A fragment, on the other hand, is more like a view include.

Much of the time, those two concepts align. A page in the workflow frequently contains exactly a single block of content. As you have, wisely, noticed, though, when you get more screen real estate (on a tablet), it is entirely possible that a single activity will display more than one fragment.

A single activity, on a tablet, might show, for instance, both a list of selectable items, and the details for the currently selected item in that list. When you have less space on the screen, though, those two things would be displayed as separate workflow items. Clicking on an item in the list invokes an entirely new activity.

The content is constant. The workflow changes.

Most modern applications will use a Fragment to display Activity content. It makes the application more flexible and easier to adapt to wildly different screens.

Upvotes: 1

mmlooloo
mmlooloo

Reputation: 18977

should each fragment have its own activity?

Yes, but you can also use nested fragments.

I think this will get harder to manage.

you are right but

i think you must match your app with some other widget for example if you have multiple fragments that want to show one after the other use viewpager or you can use horizontalscrollview. you can create tabs and sync them by viewpager and so on.

Upvotes: 1

Related Questions